GuidesDispose many resources together
Dispose many resources together
Dispose several resources in reverse order, every one of them even when one throws, and choose what happens to their errors.
Code that opens several resources has to close all of them, even when one fails to close. This page shows how to dispose resources in reverse order, add one after disposal, handle the errors, dispose a list you already have, deal with items that are also IAsyncDisposable, and what to watch for.
Dispose in reverse order
Section titled “Dispose in reverse order”Disposable.Collection returns a DisposableCollection, an ICollection<IDisposable> that disposes its items in reverse order, last added first. It disposes them on its first Dispose only. Remove and Clear take items out without disposing them.
var log = new List<string>();var first = Disposable.Create(() => log.Add("first"));var second = Disposable.Create(() => log.Add("second"));var third = Disposable.Create(() => log.Add("third"));
using (var resources = Disposable.Collection(first, second, third)){ resources.Remove(second); // removing an item doesn't dispose it}
// log: "third", "first"Add after disposal
Section titled “Add after disposal”An item added to a collection that is already disposed is disposed at once and not kept, as ADR-1004 records.
var log = new List<string>();var resources = Disposable.Collection();resources.Dispose();var lateItem = Disposable.Create(() => log.Add("late item closed"));
resources.Add(lateItem); // disposed at once, not kept
// log: "late item closed"; resources.Count == 0The asynchronous collection does the same through AddAsync:
var log = new List<string>();var resources = AsyncDisposable.Collection();await resources.DisposeAsync();var lateItem = AsyncDisposable.Create(() => log.Add("late item closed"));
await resources.AddAsync(lateItem); // disposed at once, not kept; Add would throw ObjectDisposedException
// log: "late item closed"; resources.Count == 0Handle the errors
Section titled “Handle the errors”A collection disposes every item even when one throws. One failure is rethrown as it is; several are thrown together as one AggregateException whose inner exceptions are in disposal order.
var first = Disposable.Create(() => throw new InvalidOperationException("first"));var second = Disposable.Create(() => throw new InvalidOperationException("second"));var resources = Disposable.Collection(first, second);
AggregateException? failure = null;try{ resources.Dispose();}catch (AggregateException exception){ failure = exception; // InnerExceptions: "second", then "first", the order they were disposed in}Disposable.CollectionIgnoringExceptions and DisposeAllIgnoringExceptions() ignore the failures instead.
var log = new List<string>();var first = Disposable.Create(() => log.Add("first"));var failing = Disposable.Create(() => throw new InvalidOperationException("Failed to close."));var third = Disposable.Create(() => log.Add("third"));var resources = Disposable.CollectionIgnoringExceptions(first, failing, third);
resources.Dispose(); // log: "third", "first": the failure is ignoredDispose a list you already have
Section titled “Dispose a list you already have”DisposeAll() disposes the items of any IEnumerable<object?> in reverse order. It skips null and every item that isn’t disposable.
var log = new List<string>();object?[] items =[ Disposable.Create(() => log.Add("first")), "not disposable", null, Disposable.Create(() => log.Add("second")),];
items.DisposeAll(); // log: "second", "first": items that aren't IDisposable are skippedDisposeAllAsync() does the same asynchronously:
var log = new List<string>();// stream is an open Stream, such as a FileStream.object[] items = [Disposable.Create(() => log.Add("disposed")), stream];
await items.DisposeAllAsync(); // DisposeAsync for the stream, then Dispose for the restItems that are also IAsyncDisposable
Section titled “Items that are also IAsyncDisposable”A type such as Stream implements both interfaces. Synchronous disposal disposes such an item through IDisposable, as ADR-1001 records. Use AsyncDisposable.Collection when you want DisposeAsync to run.
// stream is an open Stream, such as a FileStream.using (var resources = Disposable.Collection(stream)){ stream.WriteByte(42);}
// stream.Dispose ran: the collection disposes every item through IDisposablePitfalls
Section titled “Pitfalls”An item that is only IAsyncDisposable cannot be disposed synchronously. Here DisposeAll() disposes the other item first, then throws:
List<string> log = [];object[] items =[ Disposable.Create(() => log.Add("disposed")), AsyncDisposable.Create(() => log.Add("never disposed")),];
var failed = false;try{ items.DisposeAll();}catch (InvalidOperationException){ failed = true; // the other items first: log: "disposed"}- An item that is only
IAsyncDisposable.- You write
items.DisposeAll()for a list that holds such an item. - What happens: the other items are disposed, then
InvalidOperationExceptionis thrown, whichDisposeAllIgnoringExceptions()does not ignore. - Write instead:
DisposeAllAsync()orAsyncDisposable.Collection.
- You write
- Expecting
Removeto dispose.- You write
resources.Remove(item). - What happens: the item leaves the collection undisposed.
- Write instead: dispose it yourself after removing it.
- You write
Addon a disposed async collection.- You write
resources.Add(item)afterDisposeAsync. - What happens:
ObjectDisposedException, becauseAddcannot await the item’s disposal. - Write instead:
await resources.AddAsync(item), which disposes it.
- You write