async/await 與console(C#)
問題:
上一篇async/await 致WPF卡死問題(http://www.rzrgm.cn/stephen2023/p/17725159.html),介紹主線程阻塞,async/await導致卡死問題,同樣的代碼在console下卻并不會出現卡死。
static Stopwatch sw = new Stopwatch(); static void log(string message) { Console.WriteLine($"{sw.ElapsedMilliseconds}:{message} by Thread:{Thread.CurrentThread.ManagedThreadId}"); } static void Main(string[] args) { sw.Start(); log("Main() Started!"); var t = getResult().Result; log($"got result:{t}"); log("Main() is Ended!"); Console.ReadKey(); } public static async Task<int> getResult() { await Task.Delay(1000); log("get result is about to return"); return 10; }
并且await后的任務也是由“新線程”執行的,并非主線程執行。
分析:
對于如下含await的代碼
await FooAsync(); RestOfMethod();
可以類比于:
var t = FooAsync(); var currentContext = SynchronizationContext.Current; t.ContinueWith(delegate { if (currentContext == null) RestOfMethod(); else currentContext.Post(delegate { RestOfMethod(); }, null); }, TaskScheduler.Current);
WPF與Console不同的關鍵在于SynchronizationContext,對于WPF,繼承了SynchronizationContext為DispatcherSynchronizationContext 并重寫了post方法,將委托任務交由UI線程處理,而console程序并沒有,當前的SynchronizationContext為null,所以對于console程序await后續的任務任由執行await異步任務的線程執行,相當于上一篇的ConfigureAwait(false),主線程阻塞,并不會出現卡死現象。
作者:robot2017
出處:http://www.rzrgm.cn/stephen2023/p/17726385.html
版權:本文版權歸作者和博客園共有
轉載:歡迎轉載,但未經作者同意,必須保留此段聲明;必須在文章中給出原文連接;否則必究法律責任
出處:http://www.rzrgm.cn/stephen2023/p/17726385.html
版權:本文版權歸作者和博客園共有
轉載:歡迎轉載,但未經作者同意,必須保留此段聲明;必須在文章中給出原文連接;否則必究法律責任
浙公網安備 33010602011771號