c# - async 和 await 是单线程的真的吗?

标签 c# .net multithreading async-await task

我创建了以下代码:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
       {
         Console.WriteLine("M Start");
         MyMethodAsync();
         Console.WriteLine("M end");
         Console.Read();
       }

     static async Task MyMethodAsync()
     {
        await Task.Yield();
        Task<int> longRunningTask = LongRunningOperationAsync();
        Console.WriteLine("M3");
        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        Console.WriteLine(result);
     }

       static async Task<int> LongRunningOperationAsync()  
      {
        await Task.Delay(1000);
        return 1;
      }
  }
}

输出:

M Start
M end
M3
1

这很好,但是当我查看线程分析器时,它显示如下: enter image description here 然后这个: enter image description here 然后这个: enter image description here

所以看起来我生成了线程,但是从 msdn 说:

From Asynchronous Programming with Async and Await : Threads

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

我是否遗漏或不理解某些内容? 谢谢。

最佳答案

我解释how async and await work with threads and contexts在我的博客上。总之,当 await 需要等待异步操作完成时,它会“暂停”当前的 async 方法并(默认情况下)捕获一个“上下文”。

当异步操作完成时,该“上下文”用于恢复 async 方法。这个“上下文”是 SynchronizationContext.Current,除非它是 null,在这种情况下它是 TaskScheduler.Current。在您的情况下,上下文最终成为线程池上下文,因此 async 方法的其余部分被发送到线程池。如果您从 UI 线程运行相同的代码,上下文就是 UI 上下文,所有 async 方法都将在 UI 线程上恢复。

关于c# - async 和 await 是单线程的真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35483763/

相关文章:

c# - 如何确定 GDI+ 中两条线的交点?

c# - 即使用户启动模态对话框,如何使非模态对话框保持在顶部

c# - 从页面获取窗口

c# - .IsNotEqualTo 不比较 Nulls

c# - Localhost 在 Windows 上的表现更好吗?

Python 观察长时间运行的进程,在几分钟后发出警报?

c# - HttpClient PostAsync 无效的发布格式

c# - 是否存在用于检查字符串是否为空的边缘情况?

iphone - 多线程在获取照片时使用 GCD

java - 复制 ConcurrentHashMap 到 HashMap 不一致