c# - 'awaited'任务在哪里执行?

标签 c# multithreading asynchronous task-parallel-library async-await

考虑以下几点:

private async void btnSlowPoke_Click(object sender, EventArgs e)
{
    await DoItAsync();
}

private async Task<int> SomeLongJobAsync()
{
    for (int x = 0; x < 999999; x++)
    {
        //ponder my existence for one second
        await Task.Delay(1000);
    }
    return 42;
}

public async Task<int> DoItAsync()
{
    Console.Write("She'll be coming round the mountain");
    Task<int> t = SomeLongJobAsync();  //<--On what thread does this execute?
    Console.WriteLine(" when she comes.");
    return await t;
}
  1. 执行 DoItAsync() 中的第一个 Write。
  2. SomeLongJobAsync() 开始。
  3. DoItAsync() 中的 WriteLine 执行。
  4. DoItAsync() 暂停,而 SomeLongJobAsync() 一直工作直到完成。
  5. SomeLongJobAsync() 完成,因此 DoItAsync() 返回。

同时,UI 是响应式的。

SomeLongJobAsync() 在什么线程上执行?

最佳答案

简答

GUI 线程触发的async 方法将在同一线程上执行,只要有 CPU 操作 执行。其他 async 方法开始在调用线程上运行,并在 ThreadPool 线程上继续运行。

长答案

SomeLongJobAsync 开始在调用线程(打印“She'll be coming round the mountain”)上执行,直到它到达 await。然后返回一个任务,代表异步操作+它之后的延续。当整个操作完成时,任务将完成(除非由于异常或取消而提前完成)。

Task.Delay(1000) 本身正在“执行”时 there is no thread ,因为不需要。当最终 Task.Delay(1000) 结束时,需要一个线程 来恢复。它是哪个线程取决于 SynchronizationContext (默认情况下没有 none,所以线程是 ThreadPool 线程,但在 GUI 应用程序中它是单个 GUI 线程,更多 here ).该线程执行其余代码,直到它到达另一个异步点(即另一个 await)等等。

关于c# - 'awaited'任务在哪里执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24441101/

相关文章:

c# - 如何将 UTF-8 byte[] 转换为字符串

c# - 对数据库的更改已成功提交...ObjectContext 可能处于不一致状态

c# - C# 类中私有(private)、 protected 、公共(public)和内部方法的性能有什么不同吗?

java - Java中线程的生命周期是怎样的?

JavaFX 显示新标签然后 hibernate 循环的每次迭代

c# - 使用分段执行在 Azure TableClient 2.0 中进行分页

c# - 错误 NU1100 : Unable to resolve 'Microsoft. AspNetCore.SpaServices.Extensions

multithreading - 线程休眠时跳过部分循环

asynchronous - 在 actix-web 中生成从多部分读取数据

javascript - 并行与串行中的异步代码(异步和等待)