Swift Task.sleep timeout race condition in iOS 15 and iOS 16
0 reputation · 20 Apr 2022, 10:40 UTC
Developers want to guarantee that a timeout set with Task.sleep stops any further work as soon as the cancellation signal is received, preventing unnecessary execution after the deadline.
The common approach of racing Task.sleep against a task and checking Task.isCancelled after the sleep finishes creates a race window: the task may observe cancellation only after the sleep has already completed, allowing extra iterations or work to proceed beyond the intended timeout.
It remains unclear whether Apple plans to introduce an API that combines timeout and cancellation atomically, or if developers should adopt specific wrapper patterns that close this window without adding third‑party dependencies.
What are the recommended patterns to eliminate the race window using only the standard library? Does Apple intend to provide an atomic timeout‑cancellation construct in a future Swift release?