Export (0) Print
Expand All

CancellationTokenSource::Cancel Method

Communicates a request for cancellation.

Namespace:  System.Threading
Assemblies:   System.Threading.Tasks (in System.Threading.Tasks.dll)
  mscorlib (in mscorlib.dll)

void Cancel()


This CancellationTokenSource has been disposed.


An aggregate exception containing all the exceptions thrown by the registered callbacks on the associated CancellationToken.

The associated CancellationToken will be notified of the cancellation and will transition to a state where IsCancellationRequested returns true.

Any callbacks or cancelable operations registered with the CancellationToken will be executed.

Cancelable operations and callbacks registered with the token should not throw exceptions.

However, this overload of Cancel will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

The ExecutionContext that was captured when each callback was registered will be reestablished when the callback is invoked.

The following example uses a random number generator to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed.

To handle the possible cancellation of the operation, the example instantiates a CancellationTokenSource object that generates a cancellation token which is passed to a TaskFactory object. The TaskFactory object in turn passes the cancellation token to each of the tasks responsible for collecting readings for a particular instrument. The TaskFactory::ContinueWhenAll<TAntecedentResult, TResult>(array<Task<TAntecedentResult>>, Func<array<Task<TAntecedentResult>>, TResult>, CancellationToken) method is called to ensure that the mean is computed only after all readings have been gathered successfully. If a task has not because it has been cancelled, the call to the TaskFactory::ContinueWhenAll method throws an exception.

No code example is currently available or this language may not be supported.

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
© 2015 Microsoft