問題:
上一篇async/await 致WPF卡死問題(https://www.cnblogs.com/stephen2023/p/17725159.html),介紹主線程阻塞,async/await導(dǎo)致卡死問題,同樣的代碼在console下卻并不會(huì)出現(xiàn)卡死。
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后的任務(wù)也是由“新線程”執(zhí)行的,并非主線程執(zhí)行。
分析:
對(duì)于如下含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不同的關(guān)鍵在于SynchronizationContext,對(duì)于WPF,繼承了SynchronizationContext為DispatcherSynchronizationContext 并重寫了post方法,將委托任務(wù)交由UI線程處理,而console程序并沒有,當(dāng)前的SynchronizationContext為null,所以對(duì)于console程序await后續(xù)的任務(wù)任由執(zhí)行await異步任務(wù)的線程執(zhí)行,相當(dāng)于上一篇的ConfigureAwait(false),主線程阻塞,并不會(huì)出現(xiàn)卡死現(xiàn)象。
?
?
?
翻譯
搜索文章來源:http://www.zghlxwxcb.cn/news/detail-712107.html
復(fù)制文章來源地址http://www.zghlxwxcb.cn/news/detail-712107.html
到了這里,關(guān)于async/await 與console(C#)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!