C# Interview Question #70

What is CancellationToken in C#?

Async/Await, Tasks & Multithreading Mid-Level Intermediate

Quick Interview Answer

CancellationToken provides a cooperative mechanism for requesting cancellation of asynchronous or long-running operations.

Detailed Explanation

CancellationToken provides a cooperative mechanism for requesting cancellation of asynchronous or long-running operations.

The caller supplies a token, and the called operation observes it and stops when cancellation is requested. Cancellation is cooperative: the runtime does not forcibly terminate arbitrary code.

In ASP.NET Core, cancellation tokens can represent client disconnection or request cancellation and should often be passed through controllers, services, EF Core queries, and HTTP operations.

Code Example

public async Task<List<Product>> GetProductsAsync(
    CancellationToken cancellationToken)
{
    return await _context.Products
        .AsNoTracking()
        .ToListAsync(cancellationToken);
}