StartQuick start
Quick start
Install the package, then run code when a scope ends, dispose several resources in reverse order, share one resource and dispose asynchronously.
This page takes you from an empty project to code that runs when a scope ends, disposes several resources in order, shares one resource and disposes asynchronously.
Install
Section titled “Install”dotnet add package NCode.DisposablesThe package is one assembly with no dependencies. Every type is in the namespace NCode.Disposables.
Run code when a scope ends
Section titled “Run code when a scope ends”Disposable.Create turns an Action into an IDisposable whose Dispose runs it once.
List<string> log = [];
using (Disposable.Create(() => log.Add("unsubscribed"))){ log.Add("subscribed");}
// log: "subscribed", "unsubscribed"Dispose several resources
Section titled “Dispose several resources”Disposable.Collection disposes its items in reverse order, the last one added first, and disposes every item even when one throws. To go further, see how to dispose many together.
List<string> log = [];
var connection = Disposable.Create(() => log.Add("connection closed"));var cache = Disposable.Create(() => log.Add("cache flushed"));var fileLock = Disposable.Create(() => log.Add("lock released"));
using (var resources = Disposable.Collection(connection, cache, fileLock)){ // work with the three resources}
// log: "lock released", "cache flushed", "connection closed"Share one resource
Section titled “Share one resource”Each lease is a reference, and the resource is disposed when the last lease is. To go further, see how to share a resource through leases.
var log = new List<string>();var connection = Disposable.Create(() => log.Add("connection closed"));
var first = SharedReference.Create(connection);var second = first.AddReference();
first.Dispose(); // log is empty: second still holds a referencesecond.Dispose(); // log: "connection closed"Dispose asynchronously
Section titled “Dispose asynchronously”AsyncDisposable has the same members for IAsyncDisposable and await using. To go further, read about synchronous and asynchronous disposal.
List<string> log = [];
await using ( AsyncDisposable.Create(async () => { await Task.Yield(); log.Add("flushed"); })){ log.Add("writing");}
// log: "writing", "flushed"Next steps
Section titled “Next steps”- Which disposable? helps you pick the type that fits what you are doing.
- Hold a changing resource shows how to replace a resource you keep in a field, and what happens to the one it replaces.
- Hand on ownership shows how to build a resource in steps and hand it to the caller only when every step succeeds.
- Behavior lists what every type does on the first and later calls to
Dispose.