Task.Run(() MethodName()) 和 await Task.Run(async () => MethodName()) [英] Task.Run( () MethodName()) and await Task.Run(async () => MethodName())

查看:93
本文介绍了Task.Run(() MethodName()) 和 await Task.Run(async () => MethodName())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解是否使用

await Task.Run(async () => MethodName())

在 MVC 5 中的好处是可以释放长时间运行的 IO 操作的线程,同时继续并行处理其他代码任务.

in MVC 5 gives the benefits of freeing up the thread of a long running IO operation, while continuing with other code tasks in Parallel.

我知道简单地使用await MethodName()"将释放线程,但它不会移动到下一行代码单元 MethodName() 已完成执行.(如果我错了,请纠正我).

I know that simply using "await MethodName()" will free up the thread, but it will not move to the next line of code unit MethodName() is done executing. (Please correct me if I am wrong).

我希望能够在执行异步操作时释放线程,并并行执行其他代码.我想使用它来并行调用不同的数据源.这是await Task.Run(async () => MethodName())"实现的吗?

I'd like to be able to free up the thread while the async operation is executing, as well as execute other code in parallel. I'd like to use this in order to make multiple calls to different data sources in parallel. Is this what "await Task.Run(async () => MethodName())" achieves?

推荐答案

不,不要那样做.

相反,不要等到不得不等待.所以,而不是做

Instead just don't await till you have to. So instead of doing

await MethodName();
DoSomeOtherWork();

Task yourTask = MethodName();
DoSomeOtherWork();
await yourTask;

这让后台 IO 工作和您的 DoSomeOtherWork() 同时发生,而不会占用线程.

This lets both the background IO work happen and your DoSomeOtherWork() at the same time without tying up a thread.

如果您有多个 IO 任务要执行,您可以使用 Task.WhenAll

If you have multiple IO tasks to perform you can group them all together with a Task.WhenAll

Task<DbOneResults> dbOne= GetDbOneRecords();
Task<DbTwoResults> dbTwo = GetDbTwoRecords();
Task<DbThreeResults> dbThree = GetDbThreeRecords();

//This line is not necessary, but if you wanted all 3 done before you 
//started to process the results you would use this. 
await Task.WhenAll(dbOne, dbTwo, dbThree);

//Use the results from the 3 tasks, its ok to await a 2nd time, it does not hurt anything.
DbOneResults dbOneResults = await dbOne;
DbTwoResults dbTwoResults = await dbTwo;
DbThreeResults dbThreeResults = await dbThree;

这可以让所有 3 个任务同时发生,而不会占用任何线程.

This lets all 3 tasks happen at once without tying up any threads.

这篇关于Task.Run(() MethodName()) 和 await Task.Run(async () => MethodName())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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