Task.Run() 中的异步/等待操作 [英] Async/Await action within Task.Run()

查看:185
本文介绍了Task.Run() 中的异步/等待操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Task.Run(()=>{}) 将动作委托放入队列并返回任务.在 Task.Run() 中使用 async/await 有什么好处吗?我知道 Task.Run() 是必需的,因为如果我们想直接使用 await,那么调用方法将需要 Async 并会影响调用位置.

Task.Run(()=>{}) puts the action delegate into the queue and returns the task . Is there any benefit of having async/await within the Task.Run()? I understand that Task.Run() is required since if we want to use await directly, then the calling method will need to be made Async and will affect the calling places.

这是在 Task.Run() 中具有异步等待的示例代码.完整示例在此处提供:创建预先计算的任务.

Here is the sample code which has async await within Task.Run(). The full sample is provided here: Create pre-computed tasks.

Task.Run(async () => { await new WebClient().DownloadStringTaskAsync("");});

也可以这样做:

Task.Run(() => new WebClient().DownloadStringTaskAsync("").Result;);

由于 Task.Run() 和 Await 都会将工作排队并由线程池挑选,因此 Task.Run() 中的 async/await 是否可以代码>有点多余?

Since both, Task.Run() and Await will queue the work and will be picked by the thread pool, could the async/await within the Task.Run() be a bit redundant?

推荐答案

在 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.

这篇关于Task.Run() 中的异步/等待操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆