Skip to content

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.

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"

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 == 0

The 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 == 0

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 ignored

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 skipped

DisposeAllAsync() 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 rest

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 IDisposable

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 InvalidOperationException is thrown, which DisposeAllIgnoringExceptions() does not ignore.
    • Write instead: DisposeAllAsync() or AsyncDisposable.Collection.
  • Expecting Remove to dispose.
    • You write resources.Remove(item).
    • What happens: the item leaves the collection undisposed.
    • Write instead: dispose it yourself after removing it.
  • Add on a disposed async collection.
    • You write resources.Add(item) after DisposeAsync.
    • What happens: ObjectDisposedException, because Add cannot await the item’s disposal.
    • Write instead: await resources.AddAsync(item), which disposes it.