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:
{
...
}
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
Comments
Post a Comment