[英]Does Task.ContinueWith capture the calling thread context for continuation?
下面的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<Task<TResult>> continuationAction)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return this.ContinueWith(continuationAction, TaskScheduler.Current, new CancellationToken(), TaskContinuationOptions.None, ref stackMark);
}
如果任务是子任务, TaskScheduler.Current
是TaskScheduler.Default
或当前任务的TaskScheduler。 如果您不想遇到奇怪的问题 ,请始终指定任务计划程序,或者更好的是,如果可以,请使用await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.