Task.ContinueWith捕获调用线程上下文以继续吗?
下面的Test_Click
是在UI线程(使用WindowsFormsSynchronizationContext )上运行的代码的简化版本:
void Test_Click(object sender, EventArgs e) { var task = DoNavigationAsync(); task.ContinueWith((t) => { MessageBox.Show("Navigation done!"); }, TaskScheduler.FromCurrentSynchronizationContext()); }
我应该显式指定TaskScheduler.FromCurrentSynchronizationContext()
以确保将在同一UI线程上执行继续操作吗? 或者ContinueWith
自动捕获执行上下文(因此,在这种情况下使TaskScheduler
参数成为冗余)?
我认为默认情况下不会这样做(不像await
),但到目前为止我找不到在线资源来确认这一点。
默认情况下它不使用当前的同步上下文,而是使用TaskScheduler.Current
,如下面的反编译代码所示:
public Task ContinueWith(Action> continuationAction) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return this.ContinueWith(continuationAction, TaskScheduler.Current, new CancellationToken(), TaskContinuationOptions.None, ref stackMark); }
如果任务是子任务, TaskScheduler.Current
是TaskScheduler.Default
或当前任务的TaskScheduler。 如果您不想遇到奇怪的问题 ,请始终指定任务计划程序,或者更好的是,如果可以,请使用await
。