Cancellation Tokens - C# Async programming

Cancellation Tokens 


  I see cancellation tokens all the time in .NET 8 for handling long running asynchronous operations, but they have been around since asynchronous programming started. 


Parts

It has two pieces:

CancellationTokenSource - creates a cancellation token and sends a cancellation request to all copies of that token.

CancellationToken - listeners monitor the token’s current state.


Listening

Ways to Listen:  1) polling, 2)  register a callback, 3) listen to multiple tokens simultaneously.

Polling example:

while (!cancellationToken.IsCancellationRequested)
{
...
}


Cancellation source purpose

 A cancellation token gives you the right to know someone is trying to cancel something. It does not give you the right to actually signal a cancellation. Only the cancellation token source gives you that. This is by design.

// Define the cancellation token.
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
...
source.Cancel();


Reuse tokens?

No.  Once the IsCancellationRequested property in a cancellation token is set to true, it can’t be set to false again and you cant reuse the same cancellation token again after its cancelled.


Coding Considerations

1. Don't handle cancellations if too far along process
2. Propagate your CancellationToken
3. Don’t throw OperationCancelledException after done
4. Validate input before cancellation section
5. Consider not checking the token at all

Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

JSON Web Tokens

GHL > Set website so shorter URL address