Json.net Async when writing to file

Json.net has asynchronous functions for converting an object to json:

jsn = await JsonConvert.DeserializeObjectAsync<T> 

But when I want to write an object to a json file, it seems to me better to work directly with the Stream file.

So, I think it should be something like this:

  var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0)) { using (StreamWriter sw = new StreamWriter(fileStream.AsStreamForWrite())) { using (JsonWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, obj); } } 

But on the JsonSerzializer object, I cannot find async methods. Also, I think I / O operations should not fit in their own thread.

What is the recommended approach?

+6
source share
2 answers

Json.NET does not support asynchronous maladaptation / serialization. Asynchronous methods on JsonConvert are just shells on synchronous methods that run them in another thread ( which is exactly what the library shouldn't do ).

I think the best approach here is to run the file access code on another thread. This will not give you the full benefits of async (it will waste the thread), but it will not block the user interface thread.

+9
source

See also this code, which uses the correct asynchronous method (for example, it will not create huge byte arrays to avoid LOH memory allocation, it will not wait for the I / O operation to complete).

 using (var file = File.Open(destination, FileMode.Create)) { using (var memoryStream = new MemoryStream()) { 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); } 

Entire File: https://github.com/imanushin/AsyncIOComparison/blob/0e2527d5c00c2465e8fd2617ed8bcb1abb529436/IntermediateData/FileNames.cs

+4
source

All Articles