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

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

问题描述

快速提问..

为了对异步编程和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 时,控制流将返回到调用方法,并且您的 async 方法的执行在 await 之后恢复,当等待的任务已经完成.

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.

这篇关于“异步任务然后等待任务"vs “任务然后返回任务"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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