[英]CancellationTokenSource.Cancel is throwing an exception
当我阅读文档 CancellationTokenSource.Cancel 不应该抛出异常。
CancellationTokenSource.Cancel
下面调用 cts.Cancel(); 导致(不抛出)OperationCanceledException。
我对此非常有信心,就好像我注释掉那行一样,最后一个 OperationCanceledException 不会被抛出。
随着 cts.Cancel 行处于活动状态,抛出异常的行是 t2.Wait(token);
如果我有延迟 cts.Cancel(); 然后 t2.Wait(token); 不会在调用该行时立即抛出异常。
t2.等待(令牌); 仅在 cts.Cancel() 运行时抛出该异常。
这是正确的行为吗?
如果它是一致的,那么我可以接受它,但我不希望 cts.Cancel 导致异常。
我显然很困惑 - 我只是想了解这种行为,所以我可以放心地将其带到生产环境中。
现在我正在使用 BackGroundWorker 执行此操作,我认为我可以使用等待和取消使其更容易跟踪和维护。
if (token.IsCancellationRequested || ctr == 100000000)
仍然抛出 ctr == 100000000
我仍然看到内部 OperationCanceledException 被捕获而外部(较低)根本没有被抛出。
这段代码有什么问题吗?
或者这是它应该如何工作?
如果没有在 Task t2 = Task.Run 中尝试捕获,我会抛出一个未捕获的异常。
我认为这会被 t2.Wait 上的 try catch 捕获,但一次一个问题。
这是 .NET 4.5 上的控制台应用程序。
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task.Run(() =>
{
Thread.Sleep(1000);
cts.Cancel(); // this is thowing an exception that is caught on the last catch (OperationCanceledException Ex)
// according to the documentation this is not supposed
// if I comment out the cts.Cancel(); then the exeption is not thrown
if (token.IsCancellationRequested)
Console.WriteLine("Cancellation requested in Task {0}.",
Task.CurrentId);
else
Console.WriteLine("Cancellation Not requested in Task {0}.",
Task.CurrentId);
}, token);
//tried this but did not help
//Task.Run(() =>
//{
// //Thread.Sleep(1000);
// if (token.IsCancellationRequested)
// Console.WriteLine("Cancellation requested in Task {0}.",
// Task.CurrentId);
//}, token);
//Thread.Sleep(1000);
////cts.Cancel();
Task t2 = Task.Run(() =>
{
try
{
Console.WriteLine("Task t2 started Int32.MaxValue = " + Int32.MaxValue.ToString());
Thread.Sleep(4000);
for (int ctr = 0; ctr < Int32.MaxValue; ctr++)
{
if (ctr < 100 || ctr % 100000000 == 0)
{
Console.WriteLine(ctr.ToString());
}
if (token.IsCancellationRequested || ctr == 100000000) // || ctr == 100000000
{
Console.WriteLine("ThrowIfCancellationRequested in t2 Task {0}.",
Task.CurrentId);
throw new OperationCanceledException(token);
//token.ThrowIfCancellationRequested();
}
}
Console.WriteLine("Task {0} finished.",
Task.CurrentId);
}
catch (OperationCanceledException Ex)
{
//Console.WriteLine(Ex.ToString());
Console.WriteLine("OperationCanceledException in Task t2 {0}: The operation was cancelled.",
Task.CurrentId);
}
catch (Exception Ex)
{
Console.WriteLine("Task t2 = Task.Run Exception Ex" + Ex.Message);
}
});
try
{
Console.WriteLine("t2.Wait a");
t2.Wait(token);
}
catch (AggregateException e)
{
Console.WriteLine("AggregateException");
foreach (var v in e.InnerExceptions)
Console.WriteLine(e.Message + " " + v.Message);
}
catch (OperationCanceledException Ex)
{
//Console.WriteLine(Ex.ToString());
Console.WriteLine("OperationCanceledException in Task {0}: The operation was cancelled.",
t2.Id);
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
Console.WriteLine("end");
Console.ReadLine();
}
是的,这是预期的行为:接受取消标记的Task.Wait
的重载一直等到:
在后一种情况下,当Task.Wait
观察到传入的令牌已被取消时,它会抛出一个“OperationCancelledException”。 这是在您的情况下触发异常时的调用堆栈
mscorlib.dll!System.Threading.CancellationToken.ThrowOperationCanceledException() Line 505 + 0x4d bytes C#
mscorlib.dll!System.Threading.ManualResetEventSlim.Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) Line 642 C#
mscorlib.dll!System.Threading.Tasks.Task.SpinThenBlockingWait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) Line 3284 + 0xf bytes C#
mscorlib.dll!System.Threading.Tasks.Task.InternalWait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) Line 3223 + 0x10 bytes C#
mscorlib.dll!System.Threading.Tasks.Task.Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) Line 3129 + 0xc bytes C#
mscorlib.dll!System.Threading.Tasks.Task.Wait(System.Threading.CancellationToken cancellationToken) Line 3064 + 0xe bytes C#
> ConsoleApplication1.exe!ConsoleApplication1.Program.Main(string[] args) Line 82 + 0x15 bytes C#
至于问题的第二部分:如果您 - 在 t2 内删除了 try/catch 并且 - 您从未取消过令牌,
那么你最终会登陆你的外部AggregateException
处理程序(因为对t2.Wait
的调用会抛出一个带有一个内部异常的AggregateException
,这将是你抛出的OperationCanceledException
。
我可能对此有误,但您收到此异常的原因是因为您取消了放置取消语句的同一任务。 operationCanceledException MSDN 文档说明如下:-
取消线程正在执行的操作时在线程中抛出的异常。
您可以尝试将第一个任务调用修改为以下内容并检查是否仍然出现异常:-
Task.Run(() =>
{
Thread.Sleep(1000);
if (token.IsCancellationRequested)
Console.WriteLine("Cancellation requested in Task {0}.",
Task.CurrentId);
}, token);
cts.Cancel();
taskCancellationSource 的有用链接:-
http://johnbadams.wordpress.com/2012/03/10/understanding-cancellationtokensource-with-tasks/
t2.Wait(token);
应该在大约 1 秒后抛出,因为token
被取消。
线
cts.Cancel();
如果"Cancellation requested in Task {0}."
不可能抛出"Cancellation requested in Task {0}."
正如你所说的那样打印到控制台。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.