Is async/await suitable for methods that are both IO and CPU bound?

前端 未结 3 1846
野的像风
野的像风 2020-11-28 20:52

The MSDN documentation appears to state that async and await are suitable for IO-bound tasks whereas Task.Run should be used for CPU-b

3条回答
  •  遥遥无期
    2020-11-28 21:34

    There are several things to consider:

    • In a GUI application, you want as little code as possible to execute on the UI thread. In that case, offloading CPU-bound operation to another thread using Task.Run() is probably a good idea. Though the users of your code can do that themselves, if they want.
    • In something like ASP.NET application, there is no UI thread and all you care about is performance. In that case, there is some overhead in using Task.Run() instead of running the code directly, but it shouldn't be significant if the operation actually takes some time. (Also, there is some overhead in returning to the synchronization context, which is one more reason why you should use ConfigureAwait(false) for most awaits in your library code.)
    • If your method is async (which BTW should be also reflected in the name of the method, not just its return type), people will expect that it won't block the synchronization context thread, even for CPU-bound work.

    Weighting that, I think using await Task.Run() is the right choice here. It does have some overhead, but also some advantages, which can be significant.

提交回复
热议问题