⚙️ C# / .NET Intermediate

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).