“异步任务然后等待任务".与“先执行任务然后返回任务" [英] "async Task then await Task" vs "Task then return task"

查看:110
本文介绍了“异步任务然后等待任务".与“先执行任务然后返回任务"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问.

为了对异步编程和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屋!

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