相关疑难解决方法(0)

如何以及何时使用'async'和'await'

从我的理解主要事情之一asyncawait要做的就是让代码易于读写-但使用它们等于产卵后台线程来执行持续时间长的逻辑?

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

// 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 …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous async-await

989
推荐指数
19
解决办法
78万
查看次数

如果async-await没有创建任何其他线程,那么它如何使应用程序响应?

一次又一次,我看到它说使用async- await不会创建任何额外的线程.这没有任何意义,因为计算机一次看起来只做一件事以上的唯一方法就是

  • 实际上一次做多件事(并行执行,使用多个处理器)
  • 通过调度任务并在它们之间切换来模拟它(做一点A,一点点B,一点A,等等)

因此,如果async- await这些都没有,那么它如何使应用程序响应?如果只有一个线程,则调用任何方法意味着在执行任何其他操作之前等待方法完成,并且该方法中的方法必须在继续之前等待结果,依此类推.

.net c# multithreading asynchronous async-await

220
推荐指数
8
解决办法
5万
查看次数

标签 统计

.net ×2

async-await ×2

asynchronous ×2

c# ×2

multithreading ×1