When to Dispose CancellationTokenSource in Xamarin.Forms Async Operations?
0 reputation · 16 Nov 2024, 14:41 UTC
Goal
Implement graceful cancellation and timeout handling for network calls in a Xamarin.Forms page.
Constraints
CancellationTokenSource must be passed to all async methods, and the UI must be updated on the main thread. Reusing a single CTS across multiple requests risks leaking resources if not disposed, while disposing after each call may hinder cancellation of overlapping operations.
Unresolved Decision
The community lacks consensus on the best practice for disposing CTS: immediately after a single operation, at the end of the page’s lifecycle, or never (reusing a global CTS). Additionally, it is unclear whether all Xamarin-compatible HttpClient implementations honor the token for aborting requests, and how third‑party plugins behave.
Questions
- Should a CancellationTokenSource be disposed immediately after an individual async call, or only when the page is disposed?
- Does the default HttpClient in Xamarin.Forms respect CancellationToken passed to GetAsync for aborting network requests?
- What patterns can prevent memory leaks when a CTS is reused across multiple concurrent tasks within a page?