Posts

Showing posts with the label Async

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 = sou...