I am currently going through a .NET/React course and one lesson was about CancellationToken which I have seen before but never really understood. I decided to take some notes.

Cancellation Token

A CancellationToken in .NET is a mechanism that lets you signal to running code that it should stop work, usually because the operation is no longer needed or the user canceled it. It’s commonly used in asynchronous and long-running operations to make them cooperative and cancellable.

Usecase really depends on the queries we are making - how complex they are, how long they take, etc.

Testing CancellationToken

In my ActivitiesController I have passed a CancellationToken to the GetActivities method.

1
2
3
4
5
    [HttpGet]
    public async Task<ActionResult<List<Activity>>> GetActivities(CancellationToken cancellationToken)
    {
        return await Mediator.Send(new GetActivityList.Query(), cancellationToken);
    }

I can then use the CancellationToken in the GetActivityList.Handler mediator to check if the operation has been cancelled.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    public class Handler(AppDbContext context, ILogger<GetActivityList> logger) : IRequestHandler<Query, List<Activity>>
    {
        
        public async Task<List<Activity>> Handle(Query request, CancellationToken cancellationToken)
        {
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await Task.Delay(1000, cancellationToken);
                    logger.LogInformation($"Task {i} has completed.");
                }
            }
            catch (Exception e)
            {
                logger.LogInformation("Task was cancelled");
            }
            
            return await context.Activities.ToListAsync(cancellationToken);
        }
    }

And verify the result inside console.

Log