GuidesShare a resource through leases
Share a resource through leases
Give one resource to several owners through reference-counted leases, and dispose it when the last lease is released.
When several owners use one resource, none of them can dispose it alone: the last one to finish has to. A shared reference counts its leases and disposes the resource when the last lease is released. This page shows how to create the first lease, add an owner, what happens after the last lease, how to share a value that is not disposable, how to share an asynchronous resource, and what to watch for.
Create the first lease
Section titled “Create the first lease”SharedReference.Create wraps a resource in its first lease. Each lease is a SharedReferenceLease<T> that you dispose exactly once, and the resource is disposed when the last one is released.
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"Create2AddReference()3A Dispose4Another Disposefirst: the count is 1second, on the same resourcesecond.Dispose(): the resource staysfirst.Dispose(): the last release disposes itfirstsecondfirst.Dispose()first.Dispose() again: disposed while second still uses itCreate with a release actionCreate with onReleaseA second leaseOne lease releasedThe last release runs the action onceAdd an owner
Section titled “Add an owner”AddReference() on a lease returns a new lease on the same resource, for a second owner such as a background task. Disposable.Shared(value) and the AsSharedReference() extension both call SharedReference.Create.
List<string> log = [];var connection = Disposable.Create(() => log.Add("connection closed"));
using (var lease = connection.AsSharedReference()){ // a second owner, such as a background task using var worker = lease.AddReference();}
// log: "connection closed": both leases were releasedAfter the last lease
Section titled “After the last lease”Once the last lease is released, the resource is disposed and no lease can be added. AddReference and Value throw ObjectDisposedException, and TryAddReference returns false.
var resource = Disposable.Create(() => { });var lease = SharedReference.Create(resource);lease.Dispose(); // the last lease is released, so the resource is disposed
var added = lease.TryAddReference(out var extra); // false: no lease can be addedShare a value that is not disposable
Section titled “Share a value that is not disposable”Pass a release action to share a value that is not disposable, such as a rented buffer. The action runs once, on the thread that releases the last lease.
var pool = ArrayPool<byte>.Create();var buffer = pool.Rent(1024);
using (var lease = SharedReference.Create(buffer, array => pool.Return(array))){ lease.Value[0] = 42;}
// the buffer is back in the poolShare an asynchronous resource
Section titled “Share an asynchronous resource”AsyncSharedReference.Create shares a resource through asynchronous leases, which you dispose with await using. The last release awaits the resource’s DisposeAsync.
// stream is an open Stream, such as a FileStream.await using (var lease = AsyncSharedReference.Create(stream)){ lease.Value.WriteByte(42);}
// stream.DisposeAsync ran when the last lease was releasedAsSharedReference() and AsAsyncSharedReference() are two names for two interfaces, as ADR-1002 records.
// stream is an open Stream, which implements both IDisposable and IAsyncDisposable.await using (var lease = stream.AsAsyncSharedReference()){ lease.Value.WriteByte(42);}
// stream.DisposeAsync ran when the last lease was releasedPitfalls
Section titled “Pitfalls”Disposing a lease twice releases two references:
List<string> log = [];var connection = Disposable.Create(() => log.Add("closed"));var first = SharedReference.Create(connection);var second = first.AddReference();
first.Dispose();first.Dispose(); // releases a second reference: log: "closed"
// second.Value now throws ObjectDisposedException- Disposing a lease twice.
- You write
lease.Dispose()twice, or dispose a lease and a copy of it. - What happens: each call releases a reference, so the resource can be disposed while another owner still uses it.
- Write instead: dispose each lease exactly once, through
using.
- You write
- Copying a lease.
- You write
var copy = lease;, then dispose both. - What happens: a copy is the same lease, so two references are released.
- Write instead: pass the lease, and dispose it in one place.
- You write
- Using a
defaultlease.- You write
SharedReferenceLease<T> lease = default;thenlease.Value. - What happens:
InvalidOperationException, becauseIsActiveis false. - Write instead: take a lease from
SharedReference.CreateorAddReference.
- You write