Why 'Completion' Must Mean Full Ownership Transfer in Async C# Code
A code review of a C# concurrency fix revealed that an async operation can appear finished to external observers while internal lifecycle state still marks it as active. This ordering gap creates a contract bug: a retry might attach to a stale completed task, or concurrent disposal could clash with a pending cancellation on the same shared source. The core principle identified is that completion should act as an ownership boundary — all shared resources must reach a valid owner or terminal state before a result becomes observable. The recommended fix uses an atomic transfer pattern, clearing a shared field under a state lock so only one code path holds the resource at any given time. Cancellation and disposal then occur outside the lock on the locally owned reference, eliminating the race without blocking shared-state protection on slow operations.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in