如何以及何时使用“异步”和“等待”

让人想犯罪 __ 提交于 2020-08-11 16:36:19

问题:

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? 根据我的理解, asyncawait要做的主要事情之一就是使代码易于编写和读取-但是使用它们是否等于生成后台线程来执行长时间逻辑?

I'm currently trying out the most basic example. 我目前正在尝试最基本的示例。 I've added some comments inline. 我在行中添加了一些评论。 Can you clarify it for me? 你能为我澄清一下吗?

// 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;
}

解决方案:

参考一: https://stackoom.com/question/yeTt/如何以及何时使用-异步-和-等待
参考二: https://oldbug.net/q/yeTt/How-and-when-to-use-async-and-await
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!