CodexBloom - Programming Q&A Platform

C# - Issues with Async Task Cancellation in a Timer Callback Using .NET 5

👀 Views: 368 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
c# async cancellation timer C#

I tried several approaches but none seem to work... I'm encountering a problem with cancelling a running asynchronous task in a timer callback scenario. I'm using .NET 5 and have defined a method that performs some long-running operation asynchronously. However, when I attempt to cancel the task using a CancellationToken, it seems that the cancellation is not being respected, and the operation continues to run even after I've requested cancellation. Here's my current code: ```csharp public class MyService { private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private Timer _timer; public void Start() { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(2)); } private async void DoWork(object state) { await LongRunningOperation(_cancellationTokenSource.Token); } public void Stop() { _cancellationTokenSource.Cancel(); _timer?.Change(Timeout.Infinite, 0); } private async Task LongRunningOperation(CancellationToken cancellationToken) { try { // Simulate a long-running task for (int i = 0; i < 10; i++) { cancellationToken.ThrowIfCancellationRequested(); await Task.Delay(1000); Console.WriteLine("Working..."); } } catch (OperationCanceledException) { Console.WriteLine("Operation was canceled."); } } } ``` When I call `Stop()`, I expect that the `LongRunningOperation` should terminate, but instead, I see "Working..." printed to the console even after cancellation is requested. I've ensured that I am throwing the cancellation exception properly, but it seems to be ignored in this context. I also tried changing the `DoWork` method to return `Task` instead of `void`, but then I ran into issues with the Timer callback not being able to handle it since it expects a `void` return type. Is there a recommended approach for handling async operations in timer callbacks while properly respecting cancellation requests? Am I missing something in the way I'm managing the task lifecycle? How would you solve this? I'm working on a API that needs to handle this. Any help would be greatly appreciated!