Async.WithTimeout enforcement of cancellation in CPU‑bound F# async workflows
0 reputation · 18 Oct 2024, 01:07 UTC
Goal: Ensure that an asynchronous workflow subject to Async.WithTimeout stops execution as soon as the timeout elapses, allowing any associated resources to be released promptly.
Constraint: Async.WithTimeout creates a linked CancellationTokenSource that signals after the specified interval, but it can only abort the workflow if the workflow periodically checks that token (e.g., via Async.CheckCancellationToken). In a pure CPU‑bound loop that contains no await points or cancellation checks, the linked token is ignored, the workflow continues beyond the timeout, and the timeout only affects the continuation after the workflow finishes. The F# core library does not specify a guarantee that Async.WithTimeout will always terminate the underlying operation, leaving it unclear whether developers must embed explicit cancellation checks or rely on additional patterns.
Does Async.WithTimeout guarantee cessation of the underlying async workflow after the timeout period? If not, what combination of cancellation‑aware constructs (e.g., Async.CheckCancellationToken, try/finally, or Async.Catch) should be used to enforce timely termination for CPU‑bound workflows? Should the library documentation be updated to clarify this behavior?