如何捕获CancellationToken.ThrowIfCancellationRequested

时间:2017-05-03 20:11:43

标签: c# task task-parallel-library cancellationtokensource cancellation-token

执行此部分代码时

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);

    }

2 个答案:

答案 0 :(得分:2)

由于ThrowIfCancellationRequested()抛出OperationCanceledException类型的异常,因此必须捕获OperationCanceledException或其基类之一。

https://msdn.microsoft.com/en-us/library/system.operationcanceledexception(v=vs.110).aspx

答案 1 :(得分:1)

当异步操作发生可能的大量异常时,抛出

AggregateExceptions。它们包含所有例外情况,例如链接Tasks(通过。ContinueWith)或级联async/await来电。

正如@Mitch Stewart指出的那样,在您的示例中,要处理的正确异常类型为OperationCancelledException