GuidesHand on ownership without leaking
Hand on ownership without leaking
Build a resource in steps and hand it to the caller only when every step succeeds, so a failure never leaks it.
A method that opens a connection, then performs a handshake, owns the connection until it returns it. If a step in between throws, nobody else knows the connection exists, so it leaks. This page shows how to guard what you build, guard an asynchronous resource, check where ownership is, and what to watch for.
Guard what you build
Section titled “Guard what you build”Disposable.Guard wraps a resource in a guard. The guard disposes the value when its scope ends, unless Release() returned the value first. Call Release() as the last step, and the caller becomes the owner.
var log = new List<string>();
DisposableAction Connect(bool handshakeFails){ var connection = Disposable.Create(() => log.Add("connection closed")); using var guard = Disposable.Guard(connection);
if (handshakeFails) throw new InvalidOperationException("Handshake failed."); // the guard closes the connection
return guard.Release(); // the caller owns the connection now}
using (Connect(handshakeFails: false)) { }
try{ Connect(handshakeFails: true);}catch (InvalidOperationException){ log.Add("handshake failed");}
// log: "connection closed", "connection closed", "handshake failed"Guard an asynchronous resource
Section titled “Guard an asynchronous resource”AsyncDisposable.Guard does the same for an IAsyncDisposable: write await using var guard, and a failure disposes the value asynchronously.
List<string> log = [];
async ValueTask<AsyncDisposableAction> OpenAsync(bool handshakeFails){ var connection = AsyncDisposable.Create(() => log.Add("connection closed")); await using var guard = AsyncDisposable.Guard(connection);
await Task.Yield();
if (handshakeFails) { // the guard closes the connection throw new InvalidOperationException("Handshake failed."); }
return guard.Release(); // the caller owns the connection now}
await using (await OpenAsync(handshakeFails: false)) { }
try{ await OpenAsync(handshakeFails: true);}catch (InvalidOperationException){ log.Add("handshake failed");}
// log: "connection closed", "connection closed", "handshake failed"Check where ownership is
Section titled “Check where ownership is”IsReleased is true once Release() succeeded, and IsDisposed is true once the guard was disposed. Value is the guarded value either way.
Pitfalls
Section titled “Pitfalls”A guard releases ownership once:
var opened = Disposable.Create(() => { });using var guard = Disposable.Guard(opened);var connection = guard.Release(); // the caller owns it now
var rejected = false;try{ guard.Release();}catch (InvalidOperationException){ rejected = true; // ownership was released already}- Releasing twice.
- You write
guard.Release()a second time. - What happens:
InvalidOperationException. - Write instead: release once, as the last step.
- You write
- Releasing after the scope ended.
- You write
guard.Release()after theusingblock. - What happens:
ObjectDisposedException: the guard already disposed the value. - Write instead: call
Release()inside the scope.
- You write
- Returning
guard.Value.- You write
return guard.Value;. - What happens: the guard still owns the value and disposes it as the scope ends, so the caller gets a disposed resource.
- Write instead:
return guard.Release();.
- You write