如何以及何时使用“async”和“await”

2024-01-14

据我了解,主要的事情之一是async and await https://learn.microsoft.com/en-us/dotnet/csharp/async这样做的目的是使代码易于编写和阅读 - 但使用它们是否等于生成后台线程来执行长时间的逻辑?

我目前正在尝试最基本的示例。我在内联添加了一些评论。你能为我澄清一下吗?

// I don't understand 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;
}

使用时async and await编译器在后台生成一个状态机。

这是一个示例,我希望能够解释一些正在发生的高级细节:

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 second delay
    return 1;
}

好的,那么这里会发生什么:

  1. Task<int> longRunningTask = LongRunningOperationAsync();开始执行LongRunningOperation

  2. 独立工作是在假设主线程(线程 ID = 1)上完成的await longRunningTask到达了。

    现在,如果longRunningTask尚未完成并且仍在运行,MyMethodAsync()将返回到其调用方法,因此主线程不会被阻塞。当。。。的时候longRunningTask完成后,ThreadPool 中的一个线程(可以是任何线程)将返回MyMethodAsync()在之前的上下文中并继续执行(在本例中将结果打印到控制台)。

第二种情况是longRunningTask已经执行完毕并且结果可用。当到达await longRunningTask我们已经有了结果,因此代码将继续在同一个线程上执行。 (在本例中将结果打印到控制台)。当然,上面的例子不是这样的,上面有一个Task.Delay(1000)涉及。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以及何时使用“async”和“await” 的相关文章

随机推荐