Task.ContinueWith捕获调用线程上下文以继续吗?

nos*_*tio 12 .net c# asynchronous task-parallel-library async-await

Test_Click下面是代码的简化版本,其可以运行在一个UI线程(与WindowsFormsSynchronizationContext):

void Test_Click(object sender, EventArgs e)
{
    var task = DoNavigationAsync();
    task.ContinueWith((t) =>
    {
        MessageBox.Show("Navigation done!");
    }, TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)

我应该明确指定TaskScheduler.FromCurrentSynchronizationContext()以确保在同一UI线程上执行延续操作吗?或者ContinueWith自动捕获执行上下文(因此,TaskScheduler在这种情况下使参数多余)?

我认为默认情况下不会这样做(不像await),但到目前为止我找不到在线资源来确认这一点.

Jul*_*ain 7

默认情况下它不使用当前的同步上下文,但是TaskScheduler.Current,如下面的反编译代码所示:

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

TaskScheduler.Current要么TaskScheduler.Default或者如果任务为子任务,当前任务的的TaskScheduler.如果您不想遇到奇怪的问题,请始终指定任务计划程序,或者更好,await如果可以,请使用.