How can we stop an asynchronous long -running operation task?

We can use CancellationToken and pass it in the async long-running method and in the async method, we check the token for a cancel request and if one is requested we cancel the task.

e.g

async Task DoWorkAsync(CancellationToken token)
{
for (int i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested(); // stop if cancelled
await Task.Delay(1000); // simulate work
}
}

in the calling code:
--------------------

var cts = new CancellationTokenSource();
var task = DoWorkAsync(cts.token);

// Cancel after 5 seconds
cts.CancelAfter(5000);

try
{
await task;
}
catch(OperationCanceledException)
{
Console.WriteLine("Task was canceled!");
}

Example: Reading HTTP response with cancellation

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

class Program
{
static async Task Main()
{
var cts = new CancellationTokenSource();
cts.CancelAfter(3000); // cancel after 3 seconds

using var httpClient = new HttpClient();
try
{
using var response = await httpClient.GetAsync(
"https://example.com/largefile",
HttpCompletionOption.ResponseHeadersRead,
cts.Token); // pass the cancellation token

using var stream = await response.Content.ReadAsStreamAsync(cts.Token);

byte[] buffer = new byte[8192];
int bytesRead;

while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cts.Token)) > 0)
{
// Process bytes (simulate work)
Console.WriteLine($"Read {bytesRead} bytes...");
}

Console.WriteLine("Download complete!");
}
catch (OperationCanceledException)
{
Console.WriteLine("Download was canceled!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *