public static void Main() { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); In(); Console.WriteLine("run after in"); Console.Read(); } public static async void In() { var name=Name(); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("{0} run in {1}",Thread.CurrentThread.ManagedThreadId, await name ); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); } public static async Task<string> Name() { var res = Task.Run(() => { Thread.Sleep(10000); Console.WriteLine("Child is {0}",Thread.CurrentThread.ManagedThreadId); return "jacket"; }); return await res; }
运行结果:
1 1 run after in //整个顺序是Main->In->Name,然后在Name返回处直接跳出,执行var name=Name();下面代码,执行下去后遇到await name再次跳出,执行In()下方代码其他代码由Task线程执行。首先await的使用是最外层一定要套一个async函数,个人认为保证了不会跳出Main()函数。 Child is 3 1 run in jacket //Console.WriteLine("{0} run in {1}",await name,Thread.CurrentThread.ManagedThreadId);的执行结果是jacket run in 1.说明同一语句都能拆分到不同线程里执行啊 3