How to Cancel a Task in C# using Cancellation Token

How to Cancel a Long-Running Task using Cancellation Token in C#?

In this article, I am going to discuss How to Cancel a Long-Running Task in C# using Cancellation Token in C# with Examples. Please read our previous article where we discussed How to Limit the Number of Concurrent Tasks in C# using SemaphoreSlim with Examples. At the end of this article, you will understand how to use Cancellation Token in C# to cancel a long-running task

How to Cancel a Long-Running Task in C#?

When we run a long task, it is a good practice to provide our users with some mechanism to cancel the task. The .NET Framework provides Cancellation Token using which we can cancel a task.

How to use Cancellation Token to Cancel a Task in C#?

Let us see the steps or procedure to cancel a long-running task using Cancellation Token. So, what we will do here is, we are going to generate a cancellation token and we will pass that token to the task that we want to cancel. Before doing the practical implementation, let us first understand the CancellationTokenSource class.

If you go to the definition of CancellationTokenSource class, you will find the following. It is basically a class implementing the IDisposable interface. This CancellationTokenSource Signals to a CancellationToken that it should be canceled.

How to use Cancellation Token to Cancel a Task in C#?

Constructors of CancellationTokenSource Class in C#:

The CancellationTokenSource class provides the following three constructors to create an instance of CancellationTokenSource class.

  1. CancellationTokenSource(): It Initializes a new instance of the CancellationTokenSource class.
  2. CancellationTokenSource(TimeSpan delay): It initializes a new instance of the CancellationTokenSource class that will be canceled after the specified time span. Here, the parameter delay specifies the time interval to wait before canceling this CancellationTokenSource. It will throw ArgumentOutOfRangeException if delay.System.TimeSpan.TotalMilliseconds is less than -1 or greater than System.Int32.MaxValue.
  3. CancellationTokenSource(int millisecondsDelay): It initializes a new instance of the CancellationTokenSource class that will be canceled after the specified delay in milliseconds. Here, the parameter millisecondsDelay specifies the time interval in milliseconds to wait before canceling this System.Threading.CancellationTokenSource. It will throw ArgumentOutOfRangeException if millisecondsDelay is less than -1.
Properties of CancellationTokenSource class in C#:

The CancellationTokenSource class in C# provides the following two properties:

  1. public bool IsCancellationRequested { get; }: It gets whether cancellation has been requested for this CancellationTokenSource. It returns true if the cancellation has been requested for this CancellationTokenSource; otherwise, false.
  2. public CancellationToken Token { get; }: It gets the CancellationToken associated with the CancellationTokenSource. It returns the CancellationToken associated with this CancellationTokenSource. It will throw ObjectDisposedException if the token source has been disposed.
Methods of CancellationTokenSource class in C#:

The CancellationTokenSource class provides the following methods:

  1. Cancel(): It communicates a request for cancellation.
  2. Cancel(bool throwOnFirstException): It communicates a request for cancellation and specifies whether remaining callbacks and cancellable operations should be processed if an exception occurs. Here, the parameter throwOnFirstException specifies true if exceptions should immediately propagate; otherwise, false.
  3. CancelAfter(TimeSpan delay): It schedules a cancel operation on the CancellationTokenSource after the specified time span. Here, the parameter delay, specifies the time span to wait before canceling this CancellationTokenSource.
  4. CancelAfter(int millisecondsDelay): It schedules a cancel operation on this CancellationTokenSource after the specified number of milliseconds. Here, the parameter millisecondsDelay specifies the time span to wait before canceling this System.Threading.CancellationTokenSource.
  5. Dispose(): It releases all resources used by the current instance of the CancellationTokenSource class.
How to Create and use Cancellation Token in C#?

First, we need to create an instance of the CancellationTokenSource class as follows.

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

Then we need to set the time interval i.e. when this token is going to cancel the task execution. Here, we need to call the CancelAfter method if the CancellationTokenSource instance and we need to specify the time in milliseconds as follows. It is going to cancel the task after 5 seconds as we specify 5000 milliseconds.

cancellationTokenSource.CancelAfter(5000);

Next, our async method should accept the CancellationToken as a parameter. If you go to the definition of the CancellationToken class, then you will see that this class has one property called IsCancellationRequested which returns true if the cancellation has been requested for this token; otherwise, it is false. If it returns true then we need to stop the execution and return. But as a standard, we need to throw TaskCanceledException. For a better understanding, please have a look at the below image.

How to Create and use Cancellation Token in C#?

Next, while calling the LongRunningTask method, we need to pass the Cancellation Token. If you remember CancellationTokenSource class has one property called Token and that property return type is CancellationToken i.e. if we call the Token property on the CancellationTokenSource instance then we will get the CancellationToken and that cancellation token we need to pass to the LongRunningTask method as shown in the below image. Further, if you remember the LongRunningTask method throws TaskCanceledException when the task is canceled, and hence, we need to use the try-catch block to handle the exception as shown in the below image.

How to Cancel a Long-Running Task in C# using Cancellation Token in C# with Examples

I hope you understand how to create and use Cancellation Token. Let us see an example for a better understanding.

Example to Understand Cancellation Token in C#:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace AsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeMethod();
            Console.ReadKey();
        }

        private static async void SomeMethod()
        {
            int count = 10;
            Console.WriteLine("SomeMethod Method Started");

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            cancellationTokenSource.CancelAfter(5000);
            try
            {
                await LongRunningTask(count, cancellationTokenSource.Token);
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine($"{ex.Message}");
            }

            Console.WriteLine("\nSomeMethod Method Completed");
        }

        public static async Task LongRunningTask(int count, CancellationToken token)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            Console.WriteLine("\nLongRunningTask Started");

            for (int i = 1; i <= count; i++)
            {
                await Task.Delay(1000);
                Console.WriteLine("LongRunningTask Processing....");
                if (token.IsCancellationRequested)
                {
                    throw new TaskCanceledException();
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"LongRunningTask Took {stopwatch.ElapsedMilliseconds / 1000.0} Seconds for Processing");
        }
    }
}

In the above example, we are setting the count variable value to 10. That means the loop inside the LongRunningTask method is going to execute 10 times. And inside the loop, we have delayed the execution for 1 second. That means the loop will take at least 10 seconds to complete its execution. And we have set the cancellation token time to 5 seconds. And inside this method, we are checking whether we get the token cancellation request or not. If the IsCancellationRequested property returns true means 5 seconds is over and then we are throwing TaskCanceledException. So, when you run the above code, you will get the following output.

Example to Understand Cancellation Token in C#

Now, if you set the count variable value to less than 5, and if you execute the code, then you will see that the task is completed without throwing the TaskCanceledException.

Note: Instead of using the CancelAfter() method to set the time, you can also use the constructor which takes time in milliseconds or time in TimeSpan as an input parameter. For a better understanding, please have a look at the below image.

How to Cancel a Long-Running Task in C# using Cancellation Token in C# with Examples

Example:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace AsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeMethod();
            Console.ReadKey();
        }

        private static async void SomeMethod()
        {
            int count = 10;
            Console.WriteLine("SomeMethod Method Started");

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000);
            //cancellationTokenSource.CancelAfter(5000);
            try
            {
                await LongRunningTask(count, cancellationTokenSource.Token);
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine($"{ex.Message}");
            }

            Console.WriteLine("\nSomeMethod Method Completed");
        }

        public static async Task LongRunningTask(int count, CancellationToken token)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            Console.WriteLine("\nLongRunningTask Started");

            for (int i = 1; i <= count; i++)
            {
                await Task.Delay(1000);
                Console.WriteLine("LongRunningTask Processing....");
                if (token.IsCancellationRequested)
                {
                    throw new TaskCanceledException();
                }
            }

            stopwatch.Stop();
            Console.WriteLine($"LongRunningTask Took {stopwatch.ElapsedMilliseconds / 1000.0} Seconds for Processing");
        }
    }
}
Output:

How to Cancel a Long-Running Task in C# using Cancellation Token in C#

Realtime Example to understand Cancellation Token in C#:

Creating ASP.NET Web API Project

Open Visual Studio and creates a new ASP.NET Web API Project. If you are new to ASP.NET Web API, then please have a look at our ASP.NET Web API Tutorials. Here, we are creating an Empty Web API Project with the name WebAPIDemo. Once we created the Web API Project then add a Web API Controller with the name HomeController inside the Controllers folder. Once you add the HomeController then copy and paste the following code inside it. Here, we are creating an async method that returns a string and intentionally we delayed the execution for 5 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebAPIDemo.Controllers
{

    public class HomeController : ApiController
    {
        //api/greetings/name
        [Route("api/greetings/{name}")]
        [HttpGet]
        public async Task<string> GetGreetings(string name)
        {
            await Task.Delay(5000);
            return $"Hello {name}, Welcome to Web API";
        }
    }
}

Now, run the Web API application, and you can access the GetGreetings resource using the URL api/greetings/name as shown in the below image. In place of a name, you can pass any values. Please note the port number, it might be different in your case.

Realtime Example to understand Cancellation Token in C#

Calling Web API from Console Application using Cancellation Token:

Now, we will make an HTTP Request to the Web API from our Console Application. Please copy the endpoint address of the Web API. And then modify the code as follows. You need to replace the port number on which your Web API application is running. In the below example, we are making an asynchronous call to the Web API. Here, please observe the GetAsync method, the second parameter of this overloaded version taking the Cancellation Token, and internally it cancels the execution of the task after 4 seconds.

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

namespace AsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name = "James";
            SomeMethod(Name);
            Console.ReadKey();
        }

        private static async void SomeMethod(string Name)
        {
            Console.WriteLine("Some Method Started");
            using (var client = new HttpClient())
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(4000);

                client.BaseAddress = new Uri("http://localhost:58937/");
                try
                {
                    Console.WriteLine("Some Method Calling Web API");
                    HttpResponseMessage response = await client.GetAsync($"api/greetings/{Name}", cancellationTokenSource.Token);
                    string message = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(message);
                }
                catch (TaskCanceledException ex)
                {
                    Console.WriteLine($"Task Execution Cancelled: {ex.Message}");
                }

                Console.WriteLine("Some Method Completed");
            }
        }
    }
}
Output:

Cancellation Token in C# with Examples

Note: Before running the Console Application, first run the Web API application.

Now change the task cancellation time interval to 10 seconds and execute the program as follows.

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

namespace AsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name = "James";
            SomeMethod(Name);
            Console.ReadKey();
        }

        private static async void SomeMethod(string Name)
        {
            Console.WriteLine("Some Method Started");
            using (var client = new HttpClient())
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(10000);

                client.BaseAddress = new Uri("http://localhost:58937/");
                try
                {
                    Console.WriteLine("Some Method Calling Web API");
                    HttpResponseMessage response = await client.GetAsync($"api/greetings/{Name}", cancellationTokenSource.Token);
                    string message = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(message);
                }
                catch (TaskCanceledException ex)
                {
                    Console.WriteLine($"Task Execution Cancelled: {ex.Message}");
                }

                Console.WriteLine("Some Method Completed");
            }
        }
    }
}
Output:

Cancellation Token Examples in C#

This time as you can see the task is not canceled. This is because the task was completed before 10 seconds i.e. we are getting the response from API before 10 seconds.

In the next article, I am going to discuss How to Create Synchronous Method in C# using Task with Examples. Here, in this article, I try to explain How to Cancel a Long-Running Task using Cancellation Token in C# with Examples. I hope you enjoy this How to Cancel a Task in C# using Cancellation Token with Examples article.

2 thoughts on “How to Cancel a Task in C# using Cancellation Token”

  1. Guys,
    Please give your valuable feedback. And also, give your suggestions about this How to Cancel a Task in C# concept. If you have any better examples, you can also put them in the comment section. If you have any key points related to How to Cancel a Task in C#, you can also share the same.

Leave a Reply

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