GuidesRun code on dispose
Run code on dispose
Turn a delegate into a disposable that runs once, on every call, without allocating, or asynchronously.
A disposable can be nothing more than a delegate that runs when a scope ends. This page shows how to run code once or on every call, pass state to it, discard a result, run asynchronous code, avoid an allocation, return a disposable that does nothing, and what to watch for.
Run code once
Section titled “Run code once”Disposable.Create turns an Action into an IDisposable. The action runs on the first Dispose only, even when several threads dispose at once. Disposable.CreateRepeatable runs it on every call.
var count = 0;
var once = Disposable.Create(() => count++);once.Dispose();once.Dispose(); // count == 1: the action runs on the first call only
var everyTime = Disposable.CreateRepeatable(() => count++);everyTime.Dispose();everyTime.Dispose(); // count == 3: the action runs on every callPass state to the action
Section titled “Pass state to the action”The overloads that take state pass it to the action as arguments, so a static lambda captures nothing and allocates no closure. The overloads take up to eight arguments.
var stopwatch = Stopwatch.StartNew();
using (Disposable.Create(watch => watch.Stop(), stopwatch)){ // timed work}
// stopwatch.IsRunning == falseA HashSet<string> and its key work the same way:
HashSet<string> active = ["user:42"];
using (Disposable.Create(static (set, key) => set.Remove(key), active, "user:42")){ // work that reads the entry}
// active.Count == 0: a static lambda takes its state as argumentsDiscard a result
Section titled “Discard a result”The Func overloads discard the delegate’s result, so a method that returns a value can run on dispose without a wrapper.
var stack = new Stack<string>();stack.Push("request");
using (Disposable.Create(() => stack.Pop())){ // stack.Count == 1}
// stack.Count == 0: the result of Pop is discardedRun asynchronous code
Section titled “Run asynchronous code”AsyncDisposable.Create takes a Func<ValueTask>, or an Action that it runs synchronously. Its state overloads take only Func<…, ValueTask>, so a Task-returning lambda is never dropped, as ADR-1005 records.
var stream = new MemoryStream();var writer = new StreamWriter(stream);
await using (AsyncDisposable.Create(async () => await writer.FlushAsync())){ await writer.WriteAsync("hello");}
// stream.Length == 5: the writer flushed when the scope endedvar stream = new MemoryStream();var writer = new StreamWriter(stream);
await using (AsyncDisposable.Create(static w => new ValueTask(w.FlushAsync()), writer)){ await writer.WriteAsync("hello");}
// stream.Length == 5Run code without allocating
Section titled “Run code without allocating”Disposable.CreateValue returns a struct that allocates nothing. Dispose it once, through using. It runs its action on every dispose, as once, or on every call explains.
var stopwatch = Stopwatch.StartNew();
using (Disposable.CreateValue(static watch => watch.Stop(), stopwatch)){ // timed work; the struct allocates nothing}
// stopwatch.IsRunning == falseReturn a disposable that does nothing
Section titled “Return a disposable that does nothing”Disposable.Empty is a shared disposable whose Dispose does nothing, for a method that sometimes has nothing to clean up.
static IDisposable Subscribe(bool enabled) => enabled ? Disposable.Create(() => Console.WriteLine("Unsubscribed")) : Disposable.Empty;
using var subscription = Subscribe(enabled: false); // Disposable.Empty: disposing it does nothingPitfalls
Section titled “Pitfalls”A value disposable is a struct, so a copy of it runs the action again. Here the original and its copy are both disposed, and the action runs twice:
var count = new StrongBox<int>();
var scope = Disposable.CreateValue(static box => box.Value++, count);var copy = scope;
scope.Dispose();copy.Dispose(); // count.Value == 2: every copy runs the action- Copying a value disposable.
- You write
var copy = scope;and dispose both. - What happens: the action runs once per dispose of every copy.
- Write instead: dispose one value, once, through
using.
- You write
- Repeating cleanup that must run once.
- You write
Disposable.CreateRepeatable(() => pool.Return(buffer)). - What happens: a second
Disposereturns the buffer twice. - Write instead:
Disposable.Create, which runs the action once.
- You write
- Disposing a
defaultvalue disposable.- You write
ValueDisposable<Stopwatch> scope = default;. - What happens:
Disposedoes nothing, because it holds no action. - Write instead:
Disposable.CreateValue(static watch => watch.Stop(), stopwatch).
- You write