gpt4 book ai didi

c# - 为什么会出现 TaskCanceledException?

转载 作者:IT王子 更新时间:2023-10-29 03:48:03 25 4
gpt4 key购买 nike

我有以下测试代码:

void Button_Click(object sender, RoutedEventArgs e)
{
var source = new CancellationTokenSource();

var tsk1 = new Task(() => Thread1(source.Token), source.Token);
var tsk2 = new Task(() => Thread2(source.Token), source.Token);

tsk1.Start();
tsk2.Start();

source.Cancel();

try
{
Task.WaitAll(new[] {tsk1, tsk2});
}
catch (Exception ex)
{
// here exception is caught
}
}

void Thread1(CancellationToken token)
{
Thread.Sleep(2000);

// If the following line is enabled, the result is the same.
// token.ThrowIfCancellationRequested();
}

void Thread2(CancellationToken token)
{
Thread.Sleep(3000);
}

在线程方法中,我没有抛出任何异常,但我在启动任务的外部代码的 try-catch block 中得到了 TaskCanceledException。为什么会发生这种情况以及 token.ThrowIfCancellationRequested(); 在这种情况下的目的是什么。我相信只有在线程方法中调用 token.ThrowIfCancellationRequested(); 时才应该抛出异常。

最佳答案

我相信这是预期的行为,因为您正在遇到竞争条件的变化。

来自 How to: Cancel a task and its children :

The calling thread does not forcibly end the task; it only signals that cancellation is requested. If the task is already running, it is up to the user delegate to notice the request and respond appropriately. If cancellation is requested before the task runs, then the user delegate is never executed and the task object transitions into the Canceled state.

来自Task Cancellation :

You can terminate the operation by [...] simply returning from the delegate. In many scenarios this is sufficient; however, a task instance that is "canceled" in this way transitions to the RanToCompletion state, not to the Canceled state.

我有根据的猜测是,当你在你的两个任务上调用 .Start() 时,有可能一个(或两个)在你调用 之前实际上没有开始.Cancel() 在您的 CancellationTokenSource 上。我敢打赌,如果您在任务开始和取消之间至少等待三秒钟,它就不会抛出异常。此外,您还可以检查这两个任务的 .Status 属性。如果我是对的,.Status 属性应该显示为 TaskStatus.Canceled抛出异常时至少在其中之一上。

请记住,开始一个新的Task 并不能保证创建一个新的线程。由 TPL 决定什么获得新线程以及什么只是排队等待执行。

关于c# - 为什么会出现 TaskCanceledException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181855/

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