如何捕捉CancellationToken.ThrowIfCancellationRequested
How to catch CancellationToken.ThrowIfCancellationRequested
这段代码执行时
cancellationToken.ThrowIfCancellationRequested();
try
catch
块不处理 exception
。
public EnumerableObservable(IEnumerable<T> enumerable)
{
this.enumerable = enumerable;
this.cancellationSource = new CancellationTokenSource();
this.cancellationToken = cancellationSource.Token;
this.workerTask = Task.Factory.StartNew(() =>
{
try
{
foreach (var value in this.enumerable)
{
//if task cancellation triggers, raise the proper exception
//to stop task execution
cancellationToken.ThrowIfCancellationRequested();
foreach (var observer in observerList)
{
observer.OnNext(value);
}
}
}
catch (AggregateException e)
{
Console.Write(e.ToString());
}
}, this.cancellationToken);
}
由于 ThrowIfCancellationRequested() 抛出类型为 OperationCanceledException 的异常,您必须捕获 OperationCanceledException 或其基础之一 类。
https://msdn.microsoft.com/en-us/library/system.operationcanceledexception(v=vs.110).aspx
AggregateExceptions are thrown when a possible multitude of exceptions during asynchronous operations occured. They contain all exceptions that were raised e.g. in chained Tasks (via .ContinueWith) or within cascaded async/await 调用。
正如@Mitch Stewart 指出的那样,在您的示例中,要处理的正确异常类型是 OperationCancelledException。
这段代码执行时
cancellationToken.ThrowIfCancellationRequested();
try
catch
块不处理 exception
。
public EnumerableObservable(IEnumerable<T> enumerable)
{
this.enumerable = enumerable;
this.cancellationSource = new CancellationTokenSource();
this.cancellationToken = cancellationSource.Token;
this.workerTask = Task.Factory.StartNew(() =>
{
try
{
foreach (var value in this.enumerable)
{
//if task cancellation triggers, raise the proper exception
//to stop task execution
cancellationToken.ThrowIfCancellationRequested();
foreach (var observer in observerList)
{
observer.OnNext(value);
}
}
}
catch (AggregateException e)
{
Console.Write(e.ToString());
}
}, this.cancellationToken);
}
由于 ThrowIfCancellationRequested() 抛出类型为 OperationCanceledException 的异常,您必须捕获 OperationCanceledException 或其基础之一 类。
https://msdn.microsoft.com/en-us/library/system.operationcanceledexception(v=vs.110).aspx
AggregateExceptions are thrown when a possible multitude of exceptions during asynchronous operations occured. They contain all exceptions that were raised e.g. in chained Tasks (via .ContinueWith) or within cascaded async/await 调用。
正如@Mitch Stewart 指出的那样,在您的示例中,要处理的正确异常类型是 OperationCancelledException。