await 与 SynchronizationContext 关系

static async Task DoStep()
{
  //step 1 Debug.WriteLine(
"DoStep Start thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId + "|" + System.Threading.Thread.CurrentThread.IsThreadPoolThread); await Task.Run(async () => {   Debug.WriteLine("Task thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId + "|" + System.Threading.Thread.CurrentThread.IsThreadPoolThread); });
//这里会出现线程上下文切换
  //如果
SynchronizationContext.Current is not null,就使用await之前的线程,与 step1保持一致,注意不要再挂起调用前的线程,否则会出现死锁。
  //如果 SynchronizationContext.Current is null,就使用线程池中处理await的线程,与 step1 不保持一致,注意在这之后不能直接使用UI控件,只能通过this.BeginInvoke调用。
  //如Task.Run之后配置 ConfigureAwait(false),就使用线程池中处理await的线程,与 step1 不保持一致,注意在这之后不能直接使用UI控件,只能通过this.BeginInvoke调用。
  Debug.WriteLine("DoStep End thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId + "|" + System.Threading.Thread.CurrentThread.IsThreadPoolThread); 
   Debug.WriteLine(SynchronizationContext.Current == null ? "null" : SynchronizationContext.Current.ToString());  
}
原文地址:https://www.cnblogs.com/yipeng-yu/p/5511898.html