5

As it is mentioned here (great blog, btw), for correct work of CPU-bound calls, proper async calls are needed. For example, not

    await Task.Run(() => Thread.Sleep(100));

but

    await Task.Delay(100);

Is there analogue for Json.net deserializing ?

    await TaskEx.Run(() => JsonConvert.DeserializeObject<PocoProduct>(resultString));

The context of usage:

async public Task<ProductsAnswer> RequestServerAsync()
{
    // Just a wrapper for await httpWebRequest.GetResponseAsync() and await postStreamReader.ReadToEndAsync()
    var resultString = await new NetworkManager().GetAsync(Constants.SERVER_REQUEST); 

    // await TaskEx.Run(() => JsonConvert.DeserializeObject<PocoProduct>(resultString));
    var answer = await ParseProductsFromString(resultString); 

    return answer;
}

1 Answer 1

5

The point of that blog post is to avoid blocking calls for operations that aren't CPU bound, such as delaying, or disk/network IO.

Parsing JSON is an inherently CPU-bound operation; the best you can do is move that work to a different thread.

Sign up to request clarification or add additional context in comments.

8 Comments

But isn't TaskEx.Run() schedule and run Func in the background thread?
@VitaliiVasylenko: Yes. That's the best you can do.
Interestingly, Json.NET does exactly what Stephen Cleary thinks should not be done. It wraps its synchronous CPU bound methods into async methods by wrapping them with Task.Factory.StartNew such as for JsonConvert.DeserializeObjectAsync.
@SLaks It's not clear as to whether you're implying "see here for why Json.NET is justifyably written that way" or "see here for why it shouldn't be." But I definitely don't think it should be since it's not adhering to a base class/interface or acting itself as a base class.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.