等待Task.Run与等待 [英] await Task.Run vs await
问题描述
我已经在网上搜索了很多关于 Task.Run
与等待异步的问题,但是在这种特定的使用场景下,我并不真正了解其中的区别.我相信情况很简单.
I've searched the web and seen a lot of questions regarding Task.Run
vs await async, but there is this specific usage scenario where I don't not really understand the difference. Scenario is quite simple i believe.
await Task.Run(() => LongProcess());
vs
await LongProcess());
其中 LongProcess
是一个异步方法,其中包含一些异步调用,例如使用await ExecuteReaderAsync()
来调用db.
where LongProcess
is a async method with a few asynchronous calls in it like calling db with await ExecuteReaderAsync()
for instance.
问题:
在这种情况下,两者之间是否有区别?任何帮助或输入表示赞赏,谢谢!
Is there any difference between the two in this scenario? Any help or input appreciated, thanks!
推荐答案
Task.Run
可以发布要在不同线程处理的操作.那是唯一的区别.
Task.Run
may post the operation to be processed at a different thread. That's the only difference.
这可能有用-例如,如果 LongProcess
不是真正的异步,它将使调用者更快地返回.但是对于真正的异步方法而言,使用 Task.Run
毫无意义,这可能会导致不必要的浪费.
This may be of use - for example, if LongProcess
isn't truly asynchronous, it will make the caller return faster. But for a truly asynchronous method, there's no point in using Task.Run
, and it may result in unnecessary waste.
但是请小心,因为 Task.Run
的行为将根据重载分辨率而变化.在您的示例中,将选择 Func< Task>
重载,这将(正确)等待 LongProcess
完成.但是,如果使用了不返回任务的委托,则 Task.Run
将仅等待执行直到第一个 await
(请注意,这是 TaskFactory的方式).StartNew
会始终表现,因此请不要使用它.)
Be careful, though, because the behaviour of Task.Run
will change based on overload resolution. In your example, the Func<Task>
overload will be chosen, which will (correctly) wait for LongProcess
to finish. However, if a non-task-returning delegate was used, Task.Run
will only wait for execution up to the first await
(note that this is how TaskFactory.StartNew
will always behave, so don't use that).
这篇关于等待Task.Run与等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!