how to cancel task in csharp

To cancel a task in C#, you can make use of a Cancellation Token. A cancellation token is an object that is passed to a task and is monitored by the task. If the token is cancelled, the task is notified and can gracefully terminate.

Here's an example of how to cancel a task in C#:

main.cs
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        CancellationToken cancellationToken = cancellationTokenSource.Token;

        Task task = Task.Run(() =>
        {
            // Long-running code here...
            // Check for cancellation...
            if (cancellationToken.IsCancellationRequested)
            {
                Console.WriteLine("Task cancelled!");
                cancellationToken.ThrowIfCancellationRequested();
            }
        }, cancellationToken);

        // Wait 2 seconds to cancel the task...
        await Task.Delay(2000);

        cancellationTokenSource.Cancel();

        try
        {
            await task;
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Task was cancelled!");
        }
    }
}
971 chars
38 lines

In this example, we first create a CancellationTokenSource object and a CancellationToken object from it. Then we create a Task object with Task.Run() and pass in a lambda expression that contains our long-running code. Inside this lambda expression, we check for cancellation using the cancellationToken.IsCancellationRequested property. If the token is cancelled, we print a message to the console and throw an OperationCanceledException.

We then delay cancellation using the Task.Delay() method and then call the cancellationTokenSource.Cancel() method to cancel the task. Finally, we use a try-catch block to catch the OperationCanceledException that is thrown when the task is cancelled.

By using a CancellationToken in your tasks, you can gracefully cancel long-running tasks and prevent them from running indefinitely.

gistlibby LogSnag