Skip to content

ReferenceBehavior of every disposable

Behavior of every disposable

Every disposable side by side: whether it is safe to dispose twice, reports IsDisposed, allocates, has an async form and disposes a late resource.

The matrix below and Which disposable? are drawn from one data file, so they agree. Each name links its card on that page.

DisposableSafe to dispose twiceReports IsDisposedAllocation-freeSync and async formsDisposes a late resourceWhat it holdsWhat Dispose does
Disposable.CreateYesYesNoYesDoes not applyAn Action, or a Func whose result it discardsRuns the action on the first call; later calls do nothing
Disposable.CreateRepeatableNoYesNoYesDoes not applyAn ActionRuns the action on every call
Disposable.CreateValueNoNoYesYesDoes not applyA static Action<TState> and its stateRuns the action on every dispose of every copy
Disposable.CollectionYesYesNoYesYesAny number of resources, in the order you add themDisposes every item in reverse order, on the first call
Disposable.AggregateYesYesNoYesYesOne resource, or nullDisposes the resource it holds
Disposable.SerialYesYesNoYesYesOne resource, or nullDisposes the resource it holds
Disposable.SingleAssignmentYesYesNoYesYesOne resource, assigned onceDisposes the resource, if one was assigned
Disposable.GuardYesYesNoYesDoes not applyOne resource, until Release() hands it onDisposes the resource unless it was released
SharedReference.CreateNoNoNoYesDoes not applyA lease on a reference-counted resourceReleases one reference; the last release disposes the resource
Disposable.ContextYesYesNoYesDoes not applyOne resource and a SynchronizationContextDisposes the resource once, on the context
semaphore.Lock() and LockAsync()NoNoYesNoDoes not applyThe lock it tookReleases the lock on every dispose
Disposable.CancellationYesYesNoYesDoes not applyA CancellationTokenSourceCancels its token, then disposes a source it created
Disposable.EmptyYesNoYesYesDoes not applyNothingNothing
Disposable.FlagYesYesNoNoDoes not applyNothing but its flagSets IsDisposed
AsyncDisposable.AdaptYesYesNoDoes not applyDoes not applyOne IDisposableDisposes the resource once, synchronously
  • Safe to dispose twice: a second Dispose does nothing. Once, or on every call explains the types that run their action again.
  • Reports IsDisposed: it implements IDisposalStatus.
  • Allocation-free: a struct, or one shared instance.
  • Sync and async forms: Disposable and AsyncDisposable both create it.
  • Disposes a late resource: a resource handed to it after disposal is disposed at once, and “Does not apply” marks a type that is handed no resource. Disposal status and late resources explains the rule.