等待 Task.Run 与等待 [英] await Task.Run vs await

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

问题描述

我在网上搜索并看到了很多关于 Task.Run 与 await async 的问题,但是在这个特定的使用场景中,我不太明白其中的区别.我相信场景很简单.

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());

对比

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 重载,这将(正确)等待 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屋!

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