.NET Developer interview question
How do you propagate cancellation in .NET?
Accept CancellationToken at public async boundaries and pass it to every cancellable I/O call. Stop promptly without converting cancellation into a server error, and never replace a request token with CancellationToken.None.
Direct answer
What a strong answer covers
How it works
Cancellation in .NET is cooperative and flows through CancellationToken parameters. ASP.NET Core provides HttpContext.RequestAborted, which is triggered when the client disconnects; it is passed into every async database, HTTP, and queue call so the work stops instead of completing for nobody. Long CPU loops call ThrowIfCancellationRequested at safe points. An OperationCanceledException is expected and should be turned into a quiet 499-style outcome rather than a logged 500. Linked token sources combine a request token with a timeout, and background services get the host’s stopping token.
Example
A search endpoint passed cancellationToken from the action parameter into EF Core’s ToListAsync and into the HttpClient call to the ranking service; when users typed quickly and abandoned requests, the database load dropped by a third because abandoned queries were cancelled. The exception filter maps OperationCanceledException to an empty response with no error log entry.
Common mistakes
- Accepting a CancellationToken and never passing it to the calls that could honour it.
- Passing CancellationToken.None to hide a warning.
- Logging every cancellation as an error and alerting on client disconnects.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.