Skip to content

StartWhich disposable?

Which disposable?

Answer at most three questions about what should happen when a scope ends, and get the type to use, its call and what to watch for.

Pick the disposable for what should happen when a scope ends. Answer the questions, and the card for your disposable is marked below, with its call, what to watch for and the guide that goes further. The answers stay in the page’s address, so you can paste a choice into a pull request.

Answer, and the card for your disposable is marked below.

1What should happen when the scope ends?
2How often may your code run?
3Which resources, and who owns them?
4What happens to the old one when you replace it?
5Which one?
6Which one?
  1. What should happen when the scope ends?
    • Your own code runs: go to step 2.
    • Resources you hold are disposed: go to step 3.
    • A lock is released, or work is cancelled: go to step 5.
    • Nothing, or only a record that it ended: go to step 6.
    • An IDisposable is disposed by code that only takes an IAsyncDisposable: adapt to async.
  2. How often may your code run?
  3. Which resources, and who owns them?
  4. What happens to the old one when you replace it?
  5. Which one?
  6. Which one?
    • Nothing, because a method must return a disposable anyway: do nothing.
    • A record that the scope ended, to read later: record disposal.
Runs code

Disposable.Create

Run a cleanup action when a scope ends, such as unsubscribing a handler.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
var calls = 0;
var cleanup = Disposable.Create(() => calls++);
cleanup.Dispose();
cleanup.Dispose(); // calls == 1
Watch for
The action runs on the first Dispose only. Up to eight arguments pass state to a static lambda.
Async form
AsyncDisposable.Create
Runs code

Disposable.CreateRepeatable

Run an action on every Dispose call, such as counting how often a scope ends.

  • Safe to dispose twice: no
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
var calls = 0;
var cleanup = Disposable.CreateRepeatable(() => calls++);
cleanup.Dispose();
cleanup.Dispose(); // calls == 2
Watch for
Every call runs the action again, so the action must be safe to repeat.
Async form
AsyncDisposable.CreateRepeatable
Runs code

Disposable.CreateValue

Run a static action with a state value in a hot path, without allocating.

  • Safe to dispose twice: no
  • Reports IsDisposed: no
  • Allocation-free: yes
The call
var counter = new StrongBox<int>();
using (Disposable.CreateValue(static box => box.Value++, counter))
{
// a hot path: the struct allocates nothing
}
// counter.Value == 1
Watch for
It is a struct: every dispose of every copy runs the action, and default does nothing. Dispose it once, through using.
Async form
AsyncDisposable.CreateValue
Holds resources

Disposable.Collection

Dispose several resources together, the last one added first.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
var first = Disposable.Create(() => log.Add("first"));
var second = Disposable.Create(() => log.Add("second"));
using (var resources = Disposable.Collection())
{
resources.Add(first);
resources.Add(second);
}
// log: "second", "first"
Watch for
Every item is disposed even when one throws: one failure is rethrown, several as one AggregateException. CollectionIgnoringExceptions ignores them.
Async form
AsyncDisposable.Collection
Holds resources

Disposable.Aggregate

Hold one resource in a field and swap it, keeping the old one alive.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
var old = Disposable.Create(() => log.Add("old"));
using (var current = Disposable.Aggregate(old))
{
// "old" is not disposed
current.Disposable = Disposable.Create(() => log.Add("new"));
}
// log: "new"
Watch for
Replacing the resource does not dispose the old one: that is yours to do.
Async form
AsyncDisposable.Aggregate
Holds resources

Disposable.Serial

Hold one resource in a field and dispose the old one each time you replace it, such as a subscription you renew.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
var old = Disposable.Create(() => log.Add("old"));
using (var current = Disposable.Serial(old))
{
current.Disposable = Disposable.Create(() => log.Add("new")); // disposes "old"
}
// log: "old", "new"
Watch for
The async form replaces through SetDisposableAsync, which awaits the old one's disposal.
Async form
AsyncDisposable.Serial
Holds resources

Disposable.SingleAssignment

Create the holder first and give it its one resource later, such as a connection that is still opening.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
using (var pending = Disposable.SingleAssignment())
{
pending.Disposable = Disposable.Create(() => log.Add("connection closed"));
}
// log: "connection closed"
Watch for
A second assignment throws InvalidOperationException, also after disposal.
Async form
AsyncDisposable.SingleAssignment
Holds resources

Disposable.Guard

Build a resource in steps and hand it to the caller only when every step succeeds.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
var opened = Disposable.Create(() => log.Add("closed"));
DisposableAction connection;
using (var guard = Disposable.Guard(opened))
{
// a step that may throw
connection = guard.Release(); // the caller owns it now
}
// log is empty
Watch for
Return guard.Release(), not guard.Value: the guard disposes a value it still owns.
Async form
AsyncDisposable.Guard
Holds resources

Disposable.Context

Dispose a resource on the thread that owns it, such as a control on a UI thread.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
var control = Disposable.Create(() => log.Add("disposed"));
// uiContext is the SynchronizationContext captured on the UI thread.
var disposable = Disposable.Context(control, uiContext);
disposable.Dispose(); // Send: returns once the context has disposed it
Watch for
Dispose waits for the context through Send; Disposable.PostingContext posts and returns at once.
Async form
AsyncDisposable.Context
Shares a resource

SharedReference.Create

Give one expensive resource to several owners, and dispose it when the last one is done.

  • Safe to dispose twice: no
  • Reports IsDisposed: no
  • Allocation-free: no
The call
List<string> log = [];
var connection = Disposable.Create(() => log.Add("closed"));
var first = Disposable.Shared(connection);
var second = first.AddReference();
first.Dispose();
second.Dispose(); // log: "closed": the last lease disposes it
Watch for
A lease is a struct: dispose each lease exactly once, because a second dispose releases another owner's reference.
Async form
AsyncSharedReference.Create
Releases or cancels

semaphore.Lock() and LockAsync()

Release a SemaphoreSlim or a ReaderWriterLockSlim when a scope ends, without allocating.

  • Safe to dispose twice: no
  • Reports IsDisposed: no
  • Allocation-free: yes
The call
using var semaphore = new SemaphoreSlim(1, 1);
using (semaphore.Lock())
{
// semaphore.CurrentCount == 0
}
// semaphore.CurrentCount == 1
Watch for
The scope is a struct: disposing it twice releases the lock twice. ReadLock(), UpgradeableReadLock() and WriteLock() do the same for a ReaderWriterLockSlim.
Async form
None: LockAsync() waits asynchronously and returns the same scope
Releases or cancels

Disposable.Cancellation

Cancel work, such as a background loop, when a scope ends.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
var cancellation = Disposable.Cancellation();
var token = cancellation.Token;
cancellation.Dispose(); // token.IsCancellationRequested == true
Watch for
A source you pass in is cancelled but not disposed; one it creates is disposed after it is cancelled.
Async form
AsyncDisposable.Cancellation
Stands in

Disposable.Empty

Return a disposable from a method that has nothing to clean up.

  • Safe to dispose twice: yes
  • Reports IsDisposed: no
  • Allocation-free: yes
The call
IDisposable Subscribe(bool enabled) =>
enabled ? Disposable.Create(() => { }) : Disposable.Empty;
using var subscription = Subscribe(enabled: false); // Disposable.Empty
Watch for
It is one shared instance, so returning it allocates nothing.
Async form
AsyncDisposable.Empty
Stands in

Disposable.Flag

Record that a scope ended, and read it later from IsDisposed.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
var flag = Disposable.Flag();
flag.Dispose(); // flag.IsDisposed == true
Watch for
It disposes nothing: it only sets IsDisposed.
Async form
None
Bridges sync and async

AsyncDisposable.Adapt

Pass an IDisposable to code that only takes an IAsyncDisposable.

  • Safe to dispose twice: yes
  • Reports IsDisposed: yes
  • Allocation-free: no
The call
List<string> log = [];
IDisposable legacy = Disposable.Create(() => log.Add("disposed"));
await using (AsyncDisposable.Adapt(legacy))
{
// code that takes an IAsyncDisposable
}
// log: "disposed"
Watch for
It disposes the resource once; AsyncDisposable.AdaptRepeatable disposes it on every call. null throws ArgumentNullException.
Async form
It is the async form of an IDisposable

Every disposable, side by side: behavior of every disposable.