ConceptsDisposal status and late resources
Disposal status and late resources
How to tell whether a disposable is disposed, and what a holder does with a resource that arrives after it was disposed.
A disposable can report whether it was disposed, and a holder that was disposed must still do something sensible with a resource handed to it afterwards. This page explains both.
Ask whether it is disposed
Section titled “Ask whether it is disposed”Every disposable class that keeps disposal state implements IDisposalStatus, whose IsDisposed is true once disposal has started. The structs, which are the value disposables, the lock scopes and the leases, keep no state and don’t implement it, nor do the empty disposables. Disposable.Flag() disposes nothing: it only records that it was disposed, in IsDisposed. ADR-1005 records the decision.
var flag = Disposable.Flag();var cleanup = Disposable.Create(() => { });flag.Dispose();IDisposalStatus status = cleanup; // every disposable that keeps state reports it// flag.IsDisposed == true, status.IsDisposed == falseA resource that arrives after disposal
Section titled “A resource that arrives after disposal”A holder disposes such a resource at once, and a disposed holder reads null, as ADR-1004 records. An aggregate shows it:
List<string> log = [];var current = Disposable.Aggregate();current.Dispose();// disposed at oncecurrent.Disposable = Disposable.Create(() => log.Add("late resource closed"));
// log: "late resource closed"; current.Disposable == nullA single assignment holder does the same when the resource arrives after disposal:
var log = new List<string>();var pending = Disposable.SingleAssignment();pending.Dispose(); // disposed before the resource arrivedpending.Disposable = Disposable.Create(() => log.Add("late resource closed")); // disposed at once
// log: "late resource closed"Each holder has a synchronous and an asynchronous way to hand over a resource:
| Holder | Synchronous hand-off | Asynchronous hand-off |
|---|---|---|
| Aggregate | The Disposable setter disposes it |
SetDisposableAsync disposes it; the setter throws ObjectDisposedException |
| Serial | The Disposable setter disposes it |
SetDisposableAsync disposes it |
| Single assignment | A first assignment disposes it; a second throws InvalidOperationException |
SetDisposableAsync disposes it |
| Collection | Add disposes it |
AddAsync disposes it; Add throws ObjectDisposedException |
Why the holder disposes it
Section titled “Why the holder disposes it”A resource handed to a disposed holder has no owner left to dispose it, so keeping or dropping it would leak it. A disposed holder reads null, so no code reaches a disposed resource through it. To see the holders in use, hold a resource that changes.