“异步任务然后等待任务”vs“任务然后返回任务”

快速问答。

为了对异步编程和 await有一些扎实的基础理解,我想知道当涉及到多线程、执行顺序和时间时,这两个代码片段之间的区别是什么:

这个 :

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

如果我用这个例行程序来称呼它:

private async void closeButtonTask()
{
// Some Task 1
// ..


await CloseApp();


// Some Task 2
// ..
}
29339 次浏览

There are very few differences between the two approaches. Basically, they share the same semantics. However, the version with async/await wraps the execution of the inner task in an outer compiler-generated task. The non-async version does not. Thus, the non-async version is (very marginally) more efficient.

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.

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.

As there is no more code after your await, there is no need to use await anyway. Simply return the Task is enough.