Search code examples
c#tasktask-parallel-librarycancellationtokensourcecancellation-token

How to catch CancellationToken.ThrowIfCancellationRequested


When this section of code is executed

cancellationToken.ThrowIfCancellationRequested();

The try catch block doesn't handle the 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);

    }

Solution

  • 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 calls.

    As @Mitch Stewart pointed out, the correct exception-type to handle would be OperationCancelledException in your example.