GuidesHold a resource that changes
Hold a resource that changes
Keep one resource in a field and replace it: an aggregate leaves the old one to you, a serial disposable disposes it, and a single-assignment disposable takes one that arrives later.
A field that holds a connection, a subscription or a file has to decide what happens to the old resource when a new one arrives, and to the new one when the owner is already disposed. This page shows how to choose the holder, swap a resource and keep the old one, replace it and dispose the old one, replace it asynchronously, take one resource that arrives later, and what to watch for.
Choose the holder
Section titled “Choose the holder”Disposable.Aggregate holds one resource and leaves the old one to you when you replace it. Disposable.Serial disposes the old one. Disposable.SingleAssignment takes one resource, once. Disposable.Collection holds many and is covered in dispose many resources. A resource handed to a holder that is already disposed is disposed at once, as ADR-1004 records.
Dispose4Given C afterwardsDisposable.AggregateHolds AHolds B; A is not disposed, and is yours againDisposes B, the one it holdsDisposes C at onceDisposable.SerialHolds AHolds B and disposes ADisposes BDisposes C at onceDisposable.SingleAssignmentHolds AThrows; B stays yoursDisposes AThrows; C stays yoursDisposable.CollectionAdd(A): holds AAdd(B): holds A and BDisposes B, then AAdd(C) disposes C at onceInvalidOperationException.A drawing of the behavior, not a trace of a real process.Swap and keep the old one
Section titled “Swap and keep the old one”An aggregate holds one resource. Setting Disposable swaps it without disposing the old one, which stays yours. Disposing the aggregate disposes the one it holds.
var log = new List<string>();var primary = Disposable.Create(() => log.Add("primary closed"));var replica = Disposable.Create(() => log.Add("replica closed"));
using (var current = Disposable.Aggregate(primary)){ current.Disposable = replica; // swapping doesn't dispose primary primary.Dispose();}
// log: "primary closed", "replica closed"Replace and dispose the old one
Section titled “Replace and dispose the old one”A serial disposable disposes the old resource each time you set a new one, so a field never leaks the last one. Setting the instance it already holds is ignored.
var log = new List<string>();using (var subscription = Disposable.Serial()){ subscription.Disposable = Disposable.Create(() => log.Add("first closed")); subscription.Disposable = Disposable.Create(() => log.Add("second closed")); // disposes the first}
// log: "first closed", "second closed"List<string> log = [];var connection = Disposable.Create(() => log.Add("closed"));var current = Disposable.Serial(connection);
current.Disposable = connection; // the same instance: nothing is disposed
// log is emptyReplace asynchronously
Section titled “Replace asynchronously”The asynchronous holders replace through SetDisposableAsync, which awaits the old one’s disposal before it returns.
List<string> log = [];var first = AsyncDisposable.Create(() => log.Add("first closed"));var second = AsyncDisposable.Create(() => log.Add("second closed"));await using (var current = AsyncDisposable.Serial()){ await current.SetDisposableAsync(first); await current.SetDisposableAsync(second); // disposes the first}
// log: "first closed", "second closed"Take one resource that arrives later
Section titled “Take one resource that arrives later”A single-assignment disposable takes one resource, now or later. A resource assigned after the holder is disposed is disposed at once.
var log = new List<string>();var pending = Disposable.SingleAssignment();pending.Dispose(); // disposed before the resource arrivedpending.Disposable = Disposable.Create(() => log.Add("late resource closed")); // disposed at once
// log: "late resource closed"Pitfalls
Section titled “Pitfalls”A single-assignment disposable throws on a second assignment:
var pending = Disposable.SingleAssignment();pending.Disposable = Disposable.Create(() => { });
var rejected = false;try{ pending.Disposable = Disposable.Create(() => { });}catch (InvalidOperationException){ rejected = true; // it takes one resource}- Expecting an aggregate to dispose what it replaces.
- You write
current.Disposable = next;onDisposable.Aggregate. - What happens: the old resource stays alive, and nothing disposes it.
- Write instead:
Disposable.Serial, or dispose the old one yourself.
- You write
- Assigning a single-assignment disposable twice.
- You write a second
pending.Disposable = …. - What happens:
InvalidOperationException, before or after disposal. - Write instead:
Disposable.Serialwhen the resource changes.
- You write a second
- Setting a disposed async aggregate.
- You write
current.Disposable = next;on a disposedAsyncDisposable.Aggregate. - What happens:
ObjectDisposedException, because a setter cannot await the disposal. - Write instead:
await current.SetDisposableAsync(next), which disposes it.
- You write