Ivan
Ivan

Reputation: 7746

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

    }

Upvotes: 2

Views: 7806

Answers (2)

earloc
earloc

Reputation: 2090

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.

Upvotes: 2

MStew
MStew

Reputation: 1275

Since ThrowIfCancellationRequested() throws an exception of type OperationCanceledException, you must catch OperationCanceledException or one of its base classes.

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

Upvotes: 2

Related Questions