C#中Await/Async中的线程ID疑惑
今天写了个测试的代码:
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();
Console.WriteLine($"dddddddddddddd.....{Thread.CurrentThread.ManagedThreadId}");
result = 1;
把这些代码都丢在新开启的子线程中在运行了。暂时还没找到依据。我的慢慢看,有谁知道的,请帮我解惑下。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步