Skip to content

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.

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 reference
second.Dispose(); // log: "connection closed"
Type1Create2AddReference()3A Dispose4Another Dispose
Two leases, each disposed oncefirst: the count is 1second, on the same resourcesecond.Dispose(): the resource staysfirst.Dispose(): the last release disposes it
One lease disposed twicefirstsecondfirst.Dispose()first.Dispose() again: disposed while second still uses it
Create with a release actionCreate with onReleaseA second leaseOne lease releasedThe last release runs the action once
A resource, R, behind a reference count. A digit is the count; R is lit while the resource lives and struck through once it is disposed.A drawing of the behavior, not a trace of a real process.

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 released

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 added

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 pool

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 released

AsSharedReference() 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 released

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.
  • 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.
  • Using a default lease.
    • You write SharedReferenceLease<T> lease = default; then lease.Value.
    • What happens: InvalidOperationException, because IsActive is false.
    • Write instead: take a lease from SharedReference.Create or AddReference.