async和await是单线程真的吗?

时间:2016-02-18 14:11:19

标签: 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;
      }
  }
}

OutPut:

M Start
M end
M3
1

哪个好,但是当我查看Thread分析器时,它显示了这个: enter image description here 然后这个: enter image description here 然后这个: enter image description here

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

  

使用Async和Await进行异步编程:线程

     

async和await关键字不会导致其他线程   创建。异步方法不需要多线程,因为异步   方法不会在自己的线程上运行。该方法在当前运行   同步上下文并仅在线程上使用时间   方法是有效的。您可以使用Task.Run将CPU绑定的工作移动到   后台线程,但后台线程对进程没有帮助   那只是等待结果可用。

我是否遗漏或不理解某事? 感谢。

2 个答案:

答案 0 :(得分:7)

我在博客上解释how async and await work with threads and contexts。总之,当await需要等待异步操作完成时,它将&#34;暂停&#34;当前async方法和(默认情况下)捕获&#34; context&#34;。

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

答案 1 :(得分:2)

  

async和await关键字不会导致创建其他线程。

是。它将CPU绑定或I / O绑定工作从进程的线程池移动到其他线程,以便它不在UI线程或当前同步上下文上执行,它不会创建新线程,这在MSDN描述中意味着什么

相关问题