“异步任务然后等待任务".与“先执行任务然后返回任务" [英] "async Task then await Task" vs "Task then return task"
问题描述
快速提问.
为了对异步编程和await
有一些扎实的基础知识,我想知道这两个代码片段在多线程以及执行顺序和时间方面有什么区别:
In order to get some solid base understanding about Asynchronous Programming and the await
I would like to know what the difference is between these two code snippets when it comes to multi threading and the execution sequence and time:
此:
public Task CloseApp()
{
return Task.Run(
()=>{
// save database
// turn off some lights
// shutdown application
});
}
相对于此:
public async Task CloseApp()
{
await Task.Run(
()=>{
// save database
// turn off some lights
// shutdown application
});
}
如果我在此例程中调用它:
if I am calling it in this routine:
private async void closeButtonTask()
{
// Some Task 1
// ..
await CloseApp();
// Some Task 2
// ..
}
推荐答案
它几乎相同(就线程等而言).但是对于第二个(使用await
),编译器将创建更多的开销.
It is almost the same (in terms of threads etc.). But for the second one (using await
) a lot more overhead will be created by the compiler.
由编译器将声明为async
并使用await
的方法转换为状态机.因此,当您按下await
时,控制流将返回到调用方法,并且在等待的Task
完成后,在await
之后恢复async
方法的执行.
Methods declared as async
and using await
are converted into a state machine by the compiler. So when you hit the await
, the control flow is returned to the calling method and execution of your async
method is resumed after the await
when the awaited Task
has finished.
由于await
之后没有更多代码,因此无论如何都无需使用await
.只需返回Task
就足够了.
As there is no more code after your await
, there is no need to use await
anyway. Simply return the Task
is enough.
这篇关于“异步任务然后等待任务".与“先执行任务然后返回任务"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!