Code as posted will "Deadlock" in Winform App if called from main thread because you're blocking the main thread with the Wait()
.
But in console app this works. but how?
Answer is hidden in the SynchronizationContext.Current
. await
captures the "SynchronizationContext" and when the task is completed it will continue in the same "SynchronizationContext".
In winform app SynchronizationContext.Current
will be set to WindowsFormsSynchronizationContext
which will post to the call to "Message loop", but who is going to process that? out main thread is waiting in Wait()
.
In console app SynchronizationContext.Current
will not be set by default so it will be null
when no "SynchronizationContext" available for await to capture so it will schedule the continuation to ThreadPool
(TaskScheduler.Default which is ThreadpoolTaskScheduler) and so the code after await works(through threadpool thread).
Aforementioned capturing behavior can be controlled using Task.ConfigureAwait(false);
which will prevent winform app from deadlocking but code after await
no longer runs in UI thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…