Does Task.ContinueWith capture the calling thread context for continuation?

前端 未结 1 787
不思量自难忘°
不思量自难忘° 2021-01-01 22:31

The Test_Click below is a simplified version of code which runs on a UI thread (with WindowsFormsSynchronizationContext):

void Test_Click(object         


        
相关标签:
1条回答
  • 2021-01-01 23:15

    It doesn't use the current synchronization context by default, but TaskScheduler.Current, as seen in the following decompiled code:

    public Task ContinueWith(Action<Task<TResult>> continuationAction)
    {
      StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
      return this.ContinueWith(continuationAction, TaskScheduler.Current, new CancellationToken(), TaskContinuationOptions.None, ref stackMark);
    }
    

    TaskScheduler.Current is either TaskScheduler.Default or the TaskScheduler of the current task if the task is a child task. Always specify the task scheduler if you don't want to run into weird problems, or better, use await if you can.

    0 讨论(0)
提交回复
热议问题