ConceptsOnce, or on every call
Once, or on every call
Which disposables run their cleanup once however often they are disposed, which run it on every call, and why.
Disposing a disposable twice is allowed by the IDisposable contract, but what a second call does is up to the type. In this library the answer depends on the kind of type: a class runs its cleanup once, a struct runs it on every call. This page shows which is which, how the factory names tell them apart, and how threads fit in.
Classes run their cleanup once
Section titled “Classes run their cleanup once”Every disposable class takes its cleanup with an atomic operation, so the cleanup runs once even when several threads dispose it at once: one thread takes the action, and the others find it taken.
var calls = 0;var running = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously);using var finish = new ManualResetEventSlim();var cleanup = Disposable.Create(() =>{ Interlocked.Increment(ref calls); running.SetResult(); // throws if the action ever runs twice finish.Wait();});
var first = Task.Run(cleanup.Dispose);await running.Task; // one thread is inside the action
// seven more threads dispose it while the action runs: they find it takenvar others = Enumerable.Range(0, 7).Select(_ => Task.Run(cleanup.Dispose));await Task.WhenAll(others);
finish.Set();await first;// calls == 1The same holds for an action disposable disposed in sequence:
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 callThe holders swap their resource atomically, and a collection’s members take one lock while its enumeration walks a snapshot.
Structs run it on every dispose
Section titled “Structs run it on every dispose”ValueDisposable<TState>, AsyncValueDisposable<TState>, the lock scopes and the leases are readonly structs. They allocate nothing, a copy is the same disposable, and every dispose of every copy runs again. Dispose each once, through using. The reasoning is in ADR-1006.
var stopwatch = Stopwatch.StartNew();
using (Disposable.CreateValue(static watch => watch.Stop(), stopwatch)){ // timed work; the struct allocates nothing}
// stopwatch.IsRunning == falseCopying a value disposable copies the disposable, not the work it did, so each copy runs the action again:
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 actionA lock scope is a struct too, so disposing one twice releases the lock twice:
using var semaphore = new SemaphoreSlim(1, 1);var scope = semaphore.Lock();scope.Dispose(); // releases the semaphore
var failed = false;try{ scope.Dispose(); // releases it again}catch (SemaphoreFullException){ failed = true; // the count would pass its maximum, 1}The name says which
Section titled “The name says which”Where a type can behave either way, the factory’s name says which. The default is the first column, and the behavior named for the other is the second. No member takes a bool that picks a behavior (ADR-1007).
| The default | Named for the other behavior |
|---|---|
Disposable.Create |
Disposable.CreateRepeatable |
AsyncDisposable.Adapt |
AsyncDisposable.AdaptRepeatable |
Disposable.Context, through Send |
Disposable.PostingContext, through Post |
Disposable.Collection |
Disposable.CollectionIgnoringExceptions |
DisposeAll() |
DisposeAllIgnoringExceptions() |
Threads and leases
Section titled “Threads and leases”A lease’s AddReference, TryAddReference and Dispose are safe from any thread, and the release action runs once, on the thread that releases the last lease. See the behavior of every disposable for each type’s behavior side by side.