12

I am creating an application with using async-await methods. But There is a large problem for me with using them. After reading few articles I still don't know what is the best way for wrapping my heavy sync operations to async methods.

I have 2 ideas. Which one is the best?

1) Current realization.

private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
{
    var tcs = new TaskCompletionSource<List<UploadedTestModel>>();
    Task.Run(() =>
    {
        var resultList = new List<UploadedTestModel>();
        foreach (var testBody in filesContent)
        {
            try
            {
                var currentCulture = Thread.CurrentThread.CurrentCulture;
                var serializerSettings = new JsonSerializerSettings
                {
                    Culture = currentCulture
                };

                var parsedData = JsonConvert.DeserializeObject<UploadedTestModel>(testBody, serializerSettings);
                resultList.Add(parsedData);
            }
            catch(Exception exception)
            {
                tcs.SetException(exception);
            }
        }
        tcs.SetResult(resultList);
    });
    return tcs.Task;
}

I'm using Task.Run and TaskCompletionSource

2) Using only Task.Run without TaskCompletionSource

private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
{
    return Task.Run(() =>
    {
       . . . .
       return resultList;          
    });
}
9
  • Task.Run is about the best you're going to get - you can't make an inherently synchronous operation truly asynchronous by just calling it in a special way. If the operation is CPU-bound (or even just wraps something that blocks a thread), it needs to run on a thread.
    – Ant P
    Aug 9, 2015 at 18:26
  • As far as I can tell the body of foreach could run in an async manner itself (except for resultList.Add). Even after then I am not sure if JsonConvert.DeserializeObject really benefits from paralleling the task. Maybe you should use a semaphore to keep the parallel calculations limited to a specific number - say the number of CPUs? Yet again I'm not sure about the number - Are you on x64 or x86 & I'm not sure to what extend you can benefit from the .NET's thread pool mechanism - which is the underlying Task runner (Scheduler). Aug 9, 2015 at 18:46
  • & to honest I have just trusted .NET underlying mechanism for Tasks blindly and I was good. But for more heavy sort of thing you should probably better be go with something like Akka.NET. Aug 9, 2015 at 18:49
  • 1
    @Egorikas Just remember async and await act a bit different in a UI app - they retain the context. So you have to use an explicit Task initiation; and just then await that Task. Aug 9, 2015 at 19:01
  • 1
    @KavehShahbazian I got the idea. Thank you for your explanation
    – Egorikas
    Aug 9, 2015 at 19:08

1 Answer 1

24

I would use neither. You'll be lying to whoever invokes your method call. When you expose an async operation, the callers expect it to be naturally asynchronous, meaning there is no thread behind it doing work.

All your methods are inherintly synchronous, and you should expose them as so. Leave it up to the caller to decide if he wants to invoke them synchronously or use a thread and queue it there, don't decide for them.

There is great article called Should I expose asynchronous wrappers for synchronous methods? by Stephan Toub which talks about all the reasons not to do what you're trying to do. I suggest reading it.

4
  • 1
    Lucian Wischik has a video titled Async Library Methods Shouldn't Lie which says the same thing. Aug 9, 2015 at 18:44
  • 1
    @Yuval I've read this article. And after it, I started to think about my code. So,Could You explain. Do you offer make this method sync and then call it with using task(it blocks my UI thread, so I need to do something with it).
    – Egorikas
    Aug 9, 2015 at 18:45
  • Does it even make sense using synchronous operation on applications like wpf, windows forms, uwp etc? You block the UI thread and it freezes the app. In this case isnt it better to wrap as asnyc?
    – Emil
    Dec 8, 2016 at 12:08
  • 1
    @batmaci It doesn't make sense to block the UI thread, indeed. But I'd still not present methods as being asynchronous, I'd simply invoke Task.Run from the event handlers. Dec 8, 2016 at 12:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.