在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
今天写了个测试的代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApp2 { public class AwaitAsyncClassNew { public async Task<int> Show() { Console.WriteLine($"aaaaaa.....{ Thread.CurrentThread.ManagedThreadId }"); await Task.Run( () => { Console.WriteLine($"bbbbbbbbbbb.....{ Thread.CurrentThread.ManagedThreadId }"); Thread.Sleep(5000); Console.WriteLine($"cccccccccccccc.....{ Thread.CurrentThread.ManagedThreadId }"); } ); Console.WriteLine($"dddddddddddddd.....{ Thread.CurrentThread.ManagedThreadId }"); return 1; } } } 运行结果如下:
用反编译工具查看,代码经过编译后,变成如下的了:
编译后,代码用 TaskAwaiter来实现了,我又写了一个例子,代码如下: public void TestTaskAwait() { Console.WriteLine($"This is Main Start.... { Thread.CurrentThread.ManagedThreadId }"); TaskAwaiter awaiter = Task.Run(() => { Console.WriteLine($"This is Task Start.... { Thread.CurrentThread.ManagedThreadId }"); Thread.Sleep(2000); Console.WriteLine($"This is Task End.... { Thread.CurrentThread.ManagedThreadId }"); }).GetAwaiter(); while (!awaiter.IsCompleted) { Thread.Sleep(100); } awaiter.GetResult(); Console.WriteLine($"This is Main End.... { Thread.CurrentThread.ManagedThreadId }"); } 运行结果如下:
此时猜测,是代码:
<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this); 这行代码在作怪。(把当前运行的线程池改成子线程运行的线程池了)这个只是猜测 awaiter.GetResult(); 把这些代码都丢在新开启的子线程中在运行了。暂时还没找到依据。我的慢慢看,有谁知道的,请帮我解惑下。
|
请发表评论