gpt4 book ai didi

c# - 取消任务时的 OperationCanceledException VS TaskCanceledException

转载 作者:太空狗 更新时间:2023-10-29 17:45:52 27 4
gpt4 key购买 nike

以下代码创建了一个被取消的任务。 await 表达式(案例 1)抛出 System.OperationCanceledException 而同步 Wait()(案例 2)抛出 System.Threading.Tasks。 TaskCanceledException(包装在 System.AggregateException 中)。

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
public static void Main()
{
Program.MainAsync().Wait();
}

private static async Task MainAsync()
{
using(var cancellationTokenSource = new CancellationTokenSource())
{
var token = cancellationTokenSource.Token;
const int cancelationCheckTimeout = 100;

var task = Task.Run(
async () =>
{
for (var i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested();
Console.Write(".");
await Task.Delay(cancelationCheckTimeout);
}
},
cancellationTokenSource.Token
);

var cancelationDelay = 10 * cancelationCheckTimeout;
cancellationTokenSource.CancelAfter(cancelationDelay);

try
{
await task; // (1)
//task.Wait(); // (2)
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"Task.IsCanceled: {task.IsCanceled}");
Console.WriteLine($"Task.IsFaulted: {task.IsFaulted}");
Console.WriteLine($"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}");
}
}
}
}

案例 1 输出:

..........System.OperationCanceledException: The operation was canceled.
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at Program.<>c__DisplayClass1_0.<<MainAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Program.<MainAsync>d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null

案例 2 输出:

..........System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at Program.<MainAsync>d__1.MoveNext()
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null

为什么第二种情况下的 System.AggregateException 不包含 System.OperationCanceledException 作为内部异常?

我知道 ThrowIfCancellationRequested() 抛出 OperationCanceledException 并且我们可以看到在这两种情况下 Task 都进入了取消(非故障)状态。

这让我感到困惑,因为从 .NET API 取消方法在两种情况下都会产生一致的行为 - 取消的任务只会抛出 TaskCanceledException:

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
public static void Main()
{
Program.MainAsync().Wait();
}

private static async Task MainAsync()
{
using(var cancellationTokenSource = new CancellationTokenSource())
{
var token = cancellationTokenSource.Token;

var task = Task.Delay(1000, token);
cancellationTokenSource.CancelAfter(100);

try
{
await task; // (1)
//task.Wait(); // (2)
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"Task.IsCanceled: {task.IsCanceled}");
Console.WriteLine($"Task.IsFaulted: {task.IsFaulted}");
Console.WriteLine($"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}");
}
}
}
}

案例 1 输出:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Program.<MainAsync>d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null

案例 2 输出:

System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at Program.<MainAsync>d__1.MoveNext()
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null

最佳答案

这里的区别来自于使用 token.ThrowIfCancellationRequested()。此方法检查是否取消,如果请求,则专门抛出 OperationCanceledException 而不是 TaskCanceledException(可以理解为 CancellationToken 不是 TPL 独有的)。你可以看看reference source并看到它调用了这个方法:

private void ThrowOperationCanceledException()
{
throw new OperationCanceledException(Environment.GetResourceString("OperationCanceled"), this);
}

虽然“常规”取消确实会生成 TaskCanceledException。您可以看到,通过在任务有机会开始运行之前取消 token :

cancellationTokenSource.Cancel();
var task = Task.Run(() => { }, cancellationTokenSource.Token);
try
{
await task;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine($"Task.IsCanceled: {task.IsCanceled}");
Console.WriteLine($"Task.IsFaulted: {task.IsFaulted}");
Console.WriteLine($"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}");
}

输出:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Sandbox.Program.<MainAsync>d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null

传统的 .Net 方法通常不对异步 API 使用 CancellationToken.ThrowIfCancellationRequested,因为这仅适用于将工作卸载到另一个线程时。这些方法用于固有的异步操作,因此使用 CancellationToken.Register(或内部 InternalRegisterWithoutEC)监视取消。

关于c# - 取消任务时的 OperationCanceledException VS TaskCanceledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34359129/

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