内Task.Run Aync /等待动作() [英] Aync/Await action within Task.Run()

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

问题描述

Task.Run(()=> {})放动作代表到队列中,并返回任务。
是否有异步有任何好处/等待Task.Run内()?
据我所知,Task.Run(),因为如果我们要使用直接等待,然后调用方法将需要进行异步,并会影响调用的地方是必需的。

下面是一个具有异步内Task.Run等待()样本code。这里提供完整的范例: https://开头MSDN .microsoft.com / EN-US /库/ hh228607(v = vs.110)的.aspx

  Task.Run(异步()=> {等待新的WebClient()DownloadStringTaskAsync();});

另外,这可能已经完成,

  Task.Run(()=>新建的WebClient()DownloadStringTaskAsync()结果;。);

由于两个,Task.Run(),并等待将排队工作,并将由线程池来采摘,莫非异步/的Task.Run内的await()有点多余?


解决方案

  

有异步有任何好处/等待Task.Run()

之内

您也可以要求相反的问题:为什么你会换一个异步/等待code在Task.Run

?!

这是异步方法返回给调用者只要第一的await被击中(即运行在一个非完成的任务)。所以,如果一个异步方法,首先执行的连胜需要很长的时间 Task.Run 将改变行为:这将导致该方法立即返回并执行第一个连胜关于线程池。

这是在UI场景非常有用,因为这样你可以100%肯定,你是不是阻塞UI。例如:的HttpWebRequest 做DNS解析同步即使您使用的异步方法之一(这基本上是一个库问题/设计错误)。这可以暂停UI线程。所以,你可以使用Task.Run 100%确保UI永远不会阻塞超过几微秒的时间。

所以,回到原来的问题:为什么一个Task.Run身体里面等待?出于同样的原因,你通常等待:解除阻塞线程

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.

Here is the sample code which has async await within Task.Run() . The full sample is provided here : https://msdn.microsoft.com/en-us/library/hh228607(v=vs.110).aspx

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

Alternatively this could have been done ,

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

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 ?

解决方案

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

You also could ask the opposite question: Why would you wrap an async/await code in 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.

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.

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 Aync /等待动作()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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