is using an an `async` lambda with `Task.Run()` redundant?

前端 未结 2 1328
既然无缘
既然无缘 2020-11-30 06:50

I just came across some code like:

var task = Task.Run(async () => { await Foo.StartAsync(); });
task.Wait();

(No, I don\'t know the inn

相关标签:
2条回答
  • 2020-11-30 07:24

    Mostly yes.

    Using Task.Run like this is mostly used by people who don't understand how to execute an async method.

    However, there is a difference. Using Task.Run means starting the async method on a ThreadPool thread.

    This can be useful when the async method's synchronous part (the part before the first await) is substantial and the caller wants to make sure that method isn't blocking.

    This can also be used to "get out of" the current context, for example where there isn't a SynchronizationContext.

    0 讨论(0)
  • 2020-11-30 07:30

    Normally, the intended usage for Task.Run is to execute CPU-bound code on a non-UI thread. As such, it would be quite rare for it to be used with an async delegate, but it is possible (e.g., for code that has both asynchronous and CPU-bound portions).

    However, that's the intended usage. I think in your example:

    var task = Task.Run(async () => { await Foo.StartAsync(); });
    task.Wait();
    

    It's far more likely that the original author is attempting to synchronously block on asynchronous code, and is (ab)using Task.Run to avoid deadlocks common in that situation (as I describe on my blog).

    In essence, it looks like the "thread pool hack" that I describe in my article on brownfield asynchronous code.

    The best solution is to not use Task.Run or Wait:

    await Foo.StartAsync();
    

    This will cause async to grow through your code base, which is the best approach, but may cause an unacceptable amount of work for your developers right now. This is presumably why your predecessor used Task.Run(..).Wait().

    0 讨论(0)
提交回复
热议问题