Json.net Async when writing to File

Json.NET doesn't really support asynchronous de-/serialization. The async methods on JsonConvert are just wrappers over the synchronous methods that run them on another thread (which is exactly what a library shouldn't do).

I think the best approach here would be to run the file access code on another thread. This won't give you the full advantages of async (it will waste a thread), but it won't block the UI thread.


See also this code, which uses right asynchronous way (e.g. it will not create huge byte arrays to avoid LOH memory allocations, it will not wait for IO operation complete).

// create this in the constructor, stream manages can be reused
// see details in this answer https://stackoverflow.com/a/42599288/185498
var streamManager = new RecyclableMemoryStreamManager();

using (var file = File.Open(destination, FileMode.Create))
{
    using (var memoryStream = streamManager.GetStream()) // RecyclableMemoryStream will be returned, it inherits MemoryStream, however prevents data allocation into the LOH
    {
        using (var writer = new StreamWriter(memoryStream))
        {
            var serializer = JsonSerializer.CreateDefault();

            serializer.Serialize(writer, data);

            await writer.FlushAsync().ConfigureAwait(false);

            memoryStream.Seek(0, SeekOrigin.Begin);

            await memoryStream.CopyToAsync(file).ConfigureAwait(false);
        }
    }

    await file.FlushAsync().ConfigureAwait(false);
}

Whole file: https://github.com/imanushin/AsyncIOComparison/blob/0e2527d5c00c2465e8fd2617ed8bcb1abb529436/IntermediateData/FileNames.cs