gpt4 book ai didi

c# - Task.ContinueWith 是否捕获调用线程上下文以继续?

转载 作者:可可西里 更新时间:2023-11-01 08:26:59 26 4
gpt4 key购买 nike

下面的 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.CurrentTaskScheduler.Default 或当前任务的 TaskScheduler(如果任务是子任务)。如果不想遇到 weird problems,请始终指定任务计划程序,或者更好,如果可以,请使用 await

关于c# - Task.ContinueWith 是否捕获调用线程上下文以继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18312695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com