Saturday, 29 July 2023

Forced cancellation of a CancellationToken

CancellationToken are used to signal that an asynchronous task should cancelled, at some given point in the code from here on a cancellation has been signaled and downstream. Methods downstream are methods and sub methods / sub routines. We can pass a cancellation token into for example Entity Framework Core to cancel a heavy database I/O process. Cancelling a method this way can be invoked on many different ways.


Examples of ways to cancel a cancellation tokens
1. By user interface actions. Like hitting a Cancel button in the UI. For example, the REST client Insomnia allows you to do this. 2. Other means of stopping a task. Inside a browser you can stop requests by reloading a window / tab. For example - If you use Swagger API in a browser, you can refresh the Swagger web page in a tab to indicate a cancellation is desired. The suggested way to programatically cancelling a cancellation token in code is to throw a OperationCanceledException in your code. If you have the Cancellation Token Source - the CTS - you can cancel the cancellation token as you like. Most often you do not have the CTS. You can always throw an OperationCanceledException. The source code can then listen to such a cancellation if you call ThrowIfCancellationIsRequested on the cancellation token. Another way to cancel a cancellation token is to create a linked cancellation token and cancellation the cancellation token source you created for it. This is an alternative way that directly updates the cancellation of a token to be cancelled downstream in case you have some logic further upstream that still should be called instead of directly throwing an OperationCancelledException. Is it a good approach to programatically create a new cancellation token and overwrite it or should you instead just throw an OperationCancelledException ? And why not just stick to the same object ? I am overwriting the token here using ref keyword, since CancellationToken is a struct object. This makes it harder to overwite, since structs are copied by value into methods, such as an extension method. However if this is a good idea or not - I include the code here for completeness.

Defining an extension method on cancellation tokens which can cancel them

CancellationTokenExtension.cs

namespace CarvedRock.Api
{
    public static class CancellationTokenExtensions
    {
        public static void ForceCancel(ref this CancellationToken cancellationToken,
        Func<bool>? condition = null)
        {
            if (condition == null || condition.Invoke())
            {
                var cts = CancellationTokenSource.CreateLinkedTokenSource(
                cancellationToken);
                cancellationToken = cts.Token;
                cts.Cancel();
            }
        }
    }
}


Here is some sample code that shows how we can use this extension method.

Using an extension method that is cancellation cancellation tokens

ProductController.cs

    [HttpGet]
    //[ResponseCache(Duration = 90, VaryByQueryKeys = new[] { "category" })]
    public async Task> Get(CancellationToken cancellationToken, string category = "all")
    {
        cancellationToken.ForceCancel(() => category == "kayak");
        using (_logger.BeginScope("ScopeCat: {ScopeCat}", category))
        {     
            _logger.LogInformation( "Getting products in API.");
            return await _productLogic.GetProductsForCategoryAsync(category, cancellationToken);
        }
    }


So there we have it, we can either use an approach like in this article, creating a temporary new cancellation token source and then created a linked cancellation token from the original cancellation token, overwriting it, and at the same time cancel it, possible by supplying a condition to decide if we want to cancel the cancellation token or not. Or we could just throw an OperationCanceledException. In the example code above I finally make the EF code communicating with the database and supply the cancelation token into a ToListAsync method here. This makes our code cancellable, in case we for example hit big data in the database that is slow and user wants to cancel.

Using an extension method that is cancellation cancellation tokens - downstream code making use of same cancellation token passed into sub method

CarvedRockRepository.cs


  public async Task<List<Product>> GetProductsAsync(string category, CancellationToken cancellationToken)
        { 

//.. Inside GetProductAsync method receiving token - more code above here inside the method

 var productsToSerialize = await _ctx.Products.Where(p => p.Category == category || category == "all")
  .Include(p => p.Rating).ToListAsync(cancellationToken);

// more code inside method below

}
  


Note ! Remember to pass down the cancellation token to your methods and sub methods /sub routines.
Share this article on LinkedIn.

1 comment:

  1. Insomnia REST can be downloaded from here

    https://insomnia.rest/download

    ReplyDelete