等待task.run vs等待c# [英] await task.run vs await c#

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

问题描述

我已经在网上搜索了很多关于task.run与await async的问题,但是在这种特定的使用情况下,我不太了解其中的区别.我相信情况很简单.

I've searched the web and seen alot 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 vs等待c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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