如何以及何时使用`async`和`await` [英] how and when to use `async` and `await`

查看:238
本文介绍了如何以及何时使用`async`和`await`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的理解主要的事情,一个异步等待要做的就是让code容易写入和读取 - 但使用它们等于产卵后台线程来执行长时间的逻辑

我目前正在尝试的最基本的例子。我行内添加了一些意见。你能澄清一下吗?

  //我不uderstand为什么这个方法必须被标记为异步。
私人异步无效的button1_Click(对象发件人,EventArgs的发送)
{
    任务< INT>访问= DoSomethingAsync();
    //任务无关的东西在这里    //达到此行后5秒钟睡觉
    // DoSomethingAsync()方法。难道不应该立即联系?
    INT A = 1;    //从我的理解应该等待在这里完成。
    INT X =等待机会;
}异步任务< INT> DoSomethingAsync()
{
    //这是在后台线程上执行的?
    System.Threading.Thread.Sleep(5000);
    返回1;
}


解决方案

在使用异步等待编译在后台生成的状态机。

下面是关于这一点我希望我能解释一些高层次的细节,会中有一个例子:

 公共异步任务MyMethodAsync()
{
    任务< INT> longRunningTask = LongRunningOperationAsync();
    其不需要LongRunningOperationAsync的结果//独立工作可以在这里完成    //现在我们称之为等待的任务
    INT结果=等待longRunningTask;
    //使用结果
    Console.WriteLine(结果);
}公共异步任务< INT> LongRunningOperationAsync()//假设我们从这个长时间运行的操作返回一个int
{
    等待Task.Delay(1000); // 1秒延时
    返回1;
}

好了,所以这里是什么情况:


  1. 任务< INT> longRunningTask = LongRunningOperationAsync(); 开始执行LongRunningOperation


  2. 独立的工作就完成了,让我们假设主线程(线程ID = 1),那么等待longRunningTask 为止。


现在,如果 longRunningTask 还没有完成,它仍在运行, MyMethodAsync()将返回它调用的方法,从而在主线程不被封锁。当 longRunningTask 然后完成从线程池线程(可以是任何线程)将返回 MyMethodAsync()中其previous上下文并继续执行(在这种情况下打印结果到控制台)。

第二种情况是,该 longRunningTask 已完成其执行,其结果是可用的。当到达等待longRunningTask 我们已经有了结果,所以code将继续非常相同的线程上执行。 (在这种情况下,打印结果控制台)。当然,这不是对上述例子的情况下,那里有涉及 Task.Delay(1000)。

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic?

I'm currently trying out the most basic example. I've added some comments inline. Can you clarify it for me?

// i don't uderstand why this method must be marked as "async'.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is this executed on a background thread?
    System.Threading.Thread.Sleep(5000);
    return 1;
}

解决方案

When using async and await the compiler generates a state machine in the background.

Here's an example on which I hope I can explain some of the high-level details that are going on:

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); //1 seconds delay
    return 1;
}

Ok, so what happens here:

  1. Task<int> longRunningTask = LongRunningOperationAsync(); starts executing LongRunningOperation

  2. independent work is done on let's assume the Main Thread (Thread ID = 1) then await longRunningTask is reached.

Now, if the longRunningTask hasn't finished and it is still running, MyMethodAsync() will return to its calling method, thus the main thread doesn't get blocked. When the longRunningTask is done then a thread from the ThreadPool (can be any thread) will return to MyMethodAsync() in its previous context and continue execution (in this case printing the result to the console).

A second case would be that the longRunningTask has already finished its execution and the result is available. When reaching the await longRunningTaskwe already have the result so the code will continue executing on the very same thread. (in this case printing result to console). Of course this is not the case for the above example, where there's a Task.Delay(1000) involved.

这篇关于如何以及何时使用`async`和`await`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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