Task.Run() 中的异步/等待操作

更新时间:2021-07-14 09:31:51

在 Task.Run() 中使用 async/await 有什么好处

Is there any benefit of having async/await within the Task.Run()

您也可以问相反的问题:为什么要在 Task.Run 中包装 async/await 代码?!

You also could ask the opposite question: Why would you wrap an async/await code in Task.Run?!

一旦第一个等待被命中(对未完成的任务进行操作),异步方法就会返回给调用者.因此,如果异步方法的第一次执行连续"需要很长时间 Task.Run 将改变行为:它将导致该方法立即返回并在线程池上执行第一个连续".

An async method returns to the caller as soon as the first await is hit (that operates on a non-completed task). So if that first execution "streak" of an async method takes a long time Task.Run will alter behavior: It will cause the method to immediately return and execute that first "streak" on the thread-pool.

这在 UI 方案中很有用,因为这样您可以 100% 确保不会阻塞 UI.示例:即使您使用其中一种异步方法(这基本上是库错误/设计错误),HttpWebRequest 也会同步进行 DNS 解析.这可以暂停 UI 线程.因此,您可以使用 Task.Run 来 100% 确保 UI 不会被阻塞超过几微秒.

This is useful in UI scenarios because that way you can make 100% sure that you are not blocking the UI. Example: HttpWebRequestdoes DNS resolution synchronously even when you use one of the async methods (this is basically a library bug/design error). This can pause the UI thread. So you can use Task.Run to be 100% sure that the UI is never blocked for longer than a few microseconds.

那么回到最初的问题:为什么在 Task.Run 主体中等待?出于与您通常等待相同的原因:解除阻塞线程.

So back to the original question: Why await inside a Task.Run body? For the same reason you normally await: To unblock the thread.