Back to results for “Concurrency & Threading”
.NET MAUI › Concurrency & Threading

How do you cancel long-running operations in MAUI?

Advanced

Answer

Pass a CancellationToken through async calls and trigger it with a CancellationTokenSource when the user navigates away or cancels. Check the token in loops and pass it to cancellation-aware APIs (HttpClient, delays). Dispose the source and handle OperationCanceledException.
_cts = new CancellationTokenSource();
try { await _api.SearchAsync(query, _cts.Token); }
catch (OperationCanceledException) { /* ignore */ }
// On new keystroke: _cts.Cancel();
Real-world example A type-ahead search cancels the in-flight request on each new keystroke so only the latest query completes.

Common follow-ups: Where do you check the token? | What exception signals cancellation?