gpt4 book ai didi

c# - 在 Adam Freeman 的 Pro Parallel Programming in C# 示例中抛出 OperationCanceledException。这是一个错误还是我遗漏了什么?

转载 作者:太空宇宙 更新时间:2023-11-03 11:12:26 26 4
gpt4 key购买 nike

在 Adam Freeman 的 Pro .NET 4 Parallel Programming in C# 的 Visual Studio 2012 Listing_07 下的控制台应用程序中运行时,我在尝试取消任务时遇到异常。对我来说,这其中的原因似乎没有什么大不了的,因为当在任务中检测到取消尝试时,我们抛出(或看起来如此)OperationCanceledException

这是一个错误还是我遗漏了什么?问题基本上出现在他所有的任务取消示例中!我只能假设自从这本书进入商店(2010 年)以来,任务库中的某些内容发生了变化?

// create the cancellation token source
CancellationTokenSource tokenSource
= new CancellationTokenSource();

// create the cancellation token
CancellationToken token = tokenSource.Token;

// create the task
Task task = new Task(() => {
for (int i = 0; i < int.MaxValue; i++) {
if (token.IsCancellationRequested) {
Console.WriteLine("Task cancel detected");
throw new OperationCanceledException(token);
} else {
Console.WriteLine("Int value {0}", i);
}
}
}, token);

// wait for input before we start the task
Console.WriteLine("Press enter to start task");
Console.WriteLine("Press enter again to cancel task");
Console.ReadLine();

// start the task
task.Start();

// read a line from the console.
Console.ReadLine();

// cancel the task
Console.WriteLine("Cancelling task");
tokenSource.Cancel();

// wait for input before exiting
Console.WriteLine("Main method complete. Press enter to finish.");
Console.ReadLine();

最佳答案

异常被 TPL 捕获,Task 被置于 Canceled 状态。因此,虽然您会看到异常(如果您在调试器中打开了异常),但它会得到处理。

正如 leon 提到的,您应该使用 CancellationToken.ThrowIfCancellationRequested 方法,而不是显式地执行检查 + throw 自己。

此页面提供了有关取消任务的详细信息: http://msdn.microsoft.com/en-us/library/dd997396.aspx

关于c# - 在 Adam Freeman 的 Pro Parallel Programming in C# 示例中抛出 OperationCanceledException。这是一个错误还是我遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543168/

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