Json.net has the async functions for converting an object to json like:
json = await JsonConvert.DeserializeObjectAsync<T>
But when I want to write an object to a json file it seems better to me to do it directly using a file Stream.
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 can't find async methods. Also I think that IO operations shouldn't be placed in a own thread.
What is the recommended approach ?
Asynchronously converts a value of a type specified by a generic type parameter to UTF-8 encoded JSON text and writes it to a stream. The type of the value to serialize. The UTF-8 stream to write to. The value to convert. Options to control serialization behavior. A token that may be used to cancel the write operation.
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.
Writing to a file asynchronously. Is there any way to write an asynchronous function that writes to data to a file repeatedly. Yes, it's possible. Make sure that you don't open file in main thread and don't modify using another one. The exception will normally occur if you open a stream.
Asynchronously converts the value of a specified type to UTF-8 encoded JSON text and writes it to the specified stream. Converts the provided value to UTF-8 encoded JSON text and write it to the Stream. Asynchronously converts a value of a type specified by a generic type parameter to UTF-8 encoded JSON text and writes it to a stream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With