How do you cancel long-running operations in MAUI?
Short 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.
Advertisement
AModel 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.
Likely follow-ups
- Where do you check the token? | What exception signals cancellation?
Related topics