异步/等待执行差异 [英] Async/Await Execution Difference

查看:236
本文介绍了异步/等待执行差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让异步把握好/等待,我想清楚了一些困惑。有人可以请解释什么是在下面的执行方面的区别:

I'm trying to get a good grasp of async/await and I want to clear some of the confusion. Can someone please explain what would be the difference in terms of execution for the following:

// version 1
public Task Copy(string source, string destination) {
    return Task.Run(() => File.Copy(source, destination));
}

public async Task Test() {
    await Copy("test", "test2");    
    // do other stuff
}

// version 2
public async Task Copy(string source, string destination) {
    await Task.Run(() => File.Copy(source, destination));
}

public async Task Test() {
    await Copy("test", "test2");
    // ...
}

他们是否造成同一个code,为什么我会写一个比其他?

Are they resulting in the same code and why would I write one over the other ?

推荐答案

首先让我先点两个codeS是的不可以一样的。

First of let me start with the point that both codes are not same.

您VERSION1 code将创建只有一个国家机器,因为它包含的await在测试方法只。

Your version1 code will create only one "State machine" as it contains await in Test method only.

您版本2 code将创建两个状态机为复制测试方法,它增加了一些开销。

Your version2 code will create two "state machines" for Copy and Test method which adds some overhead.

为什么要使用异步的方法呢?简单只是为了让我们的code可读,优雅而对付异步任务。它使我们的code更好的避免回调和延续等。

Why do we use async methods? Simple just to make our code readable, elegant while dealing with "Asynchronous Tasks". It makes our code better avoiding callbacks and continuations etc.

让我们打破什么复制方法做,我们回答
  问题,我们是否真的需要它是异步

Let's break down what Copy method is doing and we answer the question whether we really need it to be async?

复制方法只是委托调用 Task.Run 返回,最终达到对<$完成任务C $ C> File.Copy 的完成。因此,意图很明显这里我们需要它通知 File.Copy 完成的任务。这个方法做了所有你需要什么,没有必要为它是异步来达到预期效果。

Copy method simply delegates the call to Task.Run which returns a task that eventually reaches completion on File.Copy's completion. So the intent is clear here we need a task which notifies File.Copy completion. This method does all what you need, no need for it to be async to work as expected.

所以,当你需要异步

您需要异步,当你需要更早任务的完成(续)在执行一些code。

You need async when you need to execute some code upon earlier task's completion(Continuation).

例如:

public async Task Test() 
{
    await Copy("test", "test2");
    DoPostCopied(whatever);
    await DoPostCopied2();//Etc
}

您可以仅仅通过反编译两个版本之间的验证异步和非异步方法这种差异。它是太长,将无法读取,所以我跳过在这里张贴。

You can verify this difference between async and non async method just by decompiling both versions. It is too long and won't be readable so I skipped posting it here.

结论:使用异步只有当要求。在这种情况下VERSION1更好,你应该在版本2 preFER它。

Conclusion: Use async only when required. In this case version1 is better and you should prefer it over version2.

这篇关于异步/等待执行差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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