What is a CancellationToken in C#?
Answer
A CancellationToken is the standard mechanism for cooperative cancellation of asynchronous and long-running operations in .NET. CancellationTokenSource creates and controls the token: var cts = new CancellationTokenSource();. Cancel: cts.Cancel();. Get token: var token = cts.Token;. Cancellation with timeout: var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));. In a long-running method: pass the token, periodically check token.IsCancellationRequested or call token.ThrowIfCancellationRequested(). All async I/O methods accept a CancellationToken parameter: await httpClient.GetAsync(url, cancellationToken);. Best practices: (1) Thread all async methods with CancellationToken — name it ct or cancellationToken. (2) In ASP.NET Core, use HttpContext.RequestAborted — cancels when the client disconnects. (3) Always dispose CancellationTokenSource. (4) Link tokens: CancellationTokenSource.CreateLinkedTokenSource(ct1, ct2).
Previous
What is the Task Parallel Library (TPL) in C#?
Next
What are memory-related performance features in modern C#?
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?