【问题标题】:Does Task.ContinueWith capture the calling thread context for continuation?Task.ContinueWith 是否捕获调用线程上下文以继续?
【发布时间】:2013-08-19 19:51:17
【问题描述】:

下面的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 不同),但到目前为止我找不到在线资源来确认这一点。

【问题讨论】:

    标签: c# .net asynchronous task-parallel-library async-await


    【解决方案1】:

    默认不使用当前同步上下文,而是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(如果该任务是子任务)。如果您不想遇到weird problems,请始终指定任务调度程序,或者如果可以,请使用await

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2014-07-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多