Async.Race resource cleanup and CancellationToken propagation
0 reputation · 29 Apr 2020, 02:57 UTC
Managing Abandoned Workflows in Async.Race
In F# asynchronous workflows, Async.Race is commonly used to implement timeouts by racing a primary operation against a timer. While the function returns the result of the first completed workflow, the losing workflow continues to execute in the background until it reaches a cancellation check or completes naturally.
Because Async.Race does not automatically trigger cancellation for the abandoned branch, there is a risk of resource leaks or unnecessary CPU cycles if the losing task is long-running or holds external handles.
When integrating with .NET CancellationTokenSource, the coordination between the race result and the manual cancellation of the losing task requires specific orchestration to ensure prompt cleanup.
- How can a
CancellationTokenbe dynamically linked to the losing branch of anAsync.Raceto ensure immediate termination? - What is the recommended pattern to prevent the "leaking" of the abandoned workflow without introducing blocking calls?