Din*_*kur 9 .net c# multithreading task async-await
我创建了以下代码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
M Start
M end
M3
1
Run Code Online (Sandbox Code Playgroud)
哪个好,但是当我查看Thread Profiler时,它显示了这个:
然后这个:
然后这个:

所以看起来我生成线程,但是从msdn说:
从Async和Await的异步编程:线程
async和await关键字不会导致创建其他线程.异步方法不需要多线程,因为异步方法不能在自己的线程上运行.该方法在当前同步上下文上运行,并仅在方法处于活动状态时在线程上使用时间.您可以使用Task.Run将CPU绑定的工作移动到后台线程,但后台线程无助于正在等待结果可用的进程.
我错过了什么或者不理解什么?谢谢.
我将解释如何async和await使用线程和上下文的工作在我的博客.总之,当await需要等待异步操作完成时,它将"暂停"当前async方法并(默认情况下)捕获"上下文".
当异步操作完成时,使用该"上下文"来恢复该async方法.这种"背景" SynchronizationContext.Current除非是,否则就是null这种情况TaskScheduler.Current.在您的情况下,上下文最终成为线程池上下文,因此async方法的其余部分将发送到线程池.如果从UI线程运行相同的代码,则上下文将是UI上下文,并且所有async方法将在UI线程上恢复.
| 归档时间: |
|
| 查看次数: |
5614 次 |
| 最近记录: |