CancellationTokenSource creates and controls CancellationToken instances. Code that may stop an operation keeps the source; cancelable code receives only its token, preserving a separation between requesting and observing cancellation. section 9.1 section 9.7
Calling Cancel requests cancellation; it does not forcibly terminate a thread or method. The operation must check IsCancellationRequested, and lengthy work must check periodically or accept delayed termination. section 9.1 section 9.7
Common CancellationTokenSource capabilities include:
- CancelAfter adds a timeout to a source-controlled token. section 9.7
- CreateLinkedTokenSource creates a new source whose token is canceled when any supplied token is canceled, while leaving the original tokens unchanged. section 9.5
- Register can run a callback when cancellation occurs, while CancellationToken.None represents a token that should never be canceled. section 9.7
Listing 9.1 Running a background thread forever
var thread = new Thread(BackgroundProc);
thread.Start();
Console.ReadKey();
void BackgroundProc()
{
int i=0;
while(true)
{
Console.WriteLine(i++);
}
}
Compare the simple infinite background loop with the later CancellationToken implementation, where the source requests cancellation and the worker checks its token. section 9.1
User cancellation combined with a timeout
Create a linked source from a user's CancellationToken, call CancelAfter for a ten-second limit, and pass combined.Token to an asynchronous HTTP request. Either cancellation reason then cancels the request. section 9.5

