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.
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 .
How often may your code run?
Which resources, and who owns them?
What happens to the old one when you replace it?
Which one?
Which one?
Nothing, because a method must return a disposable anyway: do nothing .
A record that the scope ended, to read later: record disposal .
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar cleanup = Disposable. Create (() => calls ++ );
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.CreateThe guide
Safe to dispose twice: no Reports IsDisposed: yes Allocation-free: novar cleanup = Disposable. CreateRepeatable (() => calls ++ );
cleanup. Dispose (); // calls == 2
Watch for Every call runs the action again, so the action must be safe to repeat.
Async form AsyncDisposable.CreateRepeatableThe guide
Safe to dispose twice: no Reports IsDisposed: no Allocation-free: yesvar counter = new StrongBox < int >();
using (Disposable. CreateValue ( static box => box.Value ++ , counter))
// a hot path: the struct allocates nothing
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.CreateValueThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar first = Disposable. Create (() => log. Add ( "first" ));
var second = Disposable. Create (() => log. Add ( "second" ));
using ( var resources = Disposable. Collection ())
// 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.CollectionThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar old = Disposable. Create (() => log. Add ( "old" ));
using ( var current = Disposable. Aggregate (old))
current.Disposable = Disposable. Create (() => log. Add ( "new" ));
Watch for Replacing the resource does not dispose the old one: that is yours to do.
Async form AsyncDisposable.AggregateThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar old = Disposable. Create (() => log. Add ( "old" ));
using ( var current = Disposable. Serial (old))
current.Disposable = Disposable. Create (() => log. Add ( "new" )); // disposes "old"
Watch for The async form replaces through SetDisposableAsync, which awaits the old one's disposal.
Async form AsyncDisposable.SerialThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: nousing ( 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.SingleAssignmentThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar opened = Disposable. Create (() => log. Add ( "closed" ));
DisposableAction connection;
using ( var guard = Disposable. Guard (opened))
connection = guard. Release (); // the caller owns it now
Watch for Return guard.Release(), not guard.Value: the guard disposes a value it still owns.
Async form AsyncDisposable.GuardThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar 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.ContextThe guide
Safe to dispose twice: no Reports IsDisposed: no Allocation-free: novar connection = Disposable. Create (() => log. Add ( "closed" ));
var first = Disposable. Shared (connection);
var second = first. AddReference ();
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.CreateThe guide
Safe to dispose twice: no Reports IsDisposed: no Allocation-free: yesusing var semaphore = new SemaphoreSlim ( 1 , 1 );
// 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 The guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar 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.CancellationThe guide
Safe to dispose twice: yes Reports IsDisposed: no Allocation-free: yesIDisposable 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.EmptyThe guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: novar flag = Disposable. Flag ();
flag. Dispose (); // flag.IsDisposed == true
Watch for It disposes nothing: it only sets IsDisposed.
Async form None The guide
Safe to dispose twice: yes Reports IsDisposed: yes Allocation-free: noIDisposable legacy = Disposable. Create (() => log. Add ( "disposed" ));
await using (AsyncDisposable. Adapt (legacy))
// code that takes an IAsyncDisposable
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 The guide
Every disposable, side by side: behavior of every disposable .