Search code examples
c#.netasynchronousserializationjson.net

When to use async versions of JsonSerializer (SerializeAsync/DeserializeAsync)?


Serializers like JsonSerializer has async version of methods.

I want to clarify in what situations to use them?

I usually use simple versions Serialize/Deserialize by default and never care about async versions. But probably it's preferable to use async versions in some cases.


Solution

  • The relevant questions here are:

    1. Do I already have the data in-process, or is the data coming in asynchronously, for example over a socket?
    2. Do I care about the overhead of blocking IO operations?

    If the data is already in a string, byte[], MemoryStream, or anything similar: then just use synchronous deserialize (etc); it'll be faster (the async machinery itself has overheads). If the data is streaming in from (or out to) an external source: consider async.

    The second question can roughly be approximated to "Am I running on a server?"; client and console applications: usually aren't going to suffer massively from an idle thread (if we ignore UI blocking, which can be avoided in other ways), where-as on server applications: idle threads (blocked on pending IO) can severely limit throughput. Servers inherently run at much higher concurrency, and threads are a limited and expensive resource.