Skip to content

Resource Lifetimes

The Course
•
30 min study

The garbage collector reclaims memory, in its own time. It doesn't know about files, connections or locks that must be released promptly. That's what Dispose is for. The hard part isn't the method but the question of ownership: whose job is it to call it?

Whoever creates, disposes

If a class creates a resource and keeps it in a field, it owns it, and should itself be IDisposable, passing the call along. A resource that was handed in usually belongs to the caller, who may want to keep using it. Mistakes here lead to leaks or to "disposed object" errors.

Owned versus borrowed C#
var shared = new Resource("shared");

using (var user = new Report(shared))
{
    user.Write();
}
Console.WriteLine($"shared still open: {!shared.Closed}");

using (var owner = new FileReport())
{
    owner.Write();
}

class Resource(string name) : IDisposable
{
    public bool Closed { get; private set; }

    public void Use()
    {
        Console.WriteLine($"using {name}");
    }

    public void Dispose()
    {
        Closed = true;
        Console.WriteLine($"closed {name}");
    }
}

class Report(Resource borrowed) : IDisposable
{
    public void Write() => borrowed.Use();

    public void Dispose()
    {
    }
}

class FileReport : IDisposable
{
    private readonly Resource owned = new("owned");

    public void Write() => owned.Use();

    public void Dispose() => owned.Dispose();
}
Check your prediction
Text
using shared
shared still open: True
using owned
closed owned

Safe to call twice

Dispose must be safe to call more than once. After disposal, other methods should throw ObjectDisposedException, not fail in some obscure way. ObjectDisposedException.ThrowIf is the one-line guard.

Idempotent disposal C#
var log = new Log();
log.Write("a");
log.Dispose();
log.Dispose();

try
{
    log.Write("b");
}
catch (ObjectDisposedException)
{
    Console.WriteLine("already closed");
}

sealed class Log : IDisposable
{
    private bool disposed;

    public void Write(string text)
    {
        ObjectDisposedException.ThrowIf(disposed, this);
        Console.WriteLine(text);
    }

    public void Dispose()
    {
        if (disposed)
        {
            return;
        }
        disposed = true;
        Console.WriteLine("flushed");
    }
}
Check your prediction
Text
a
flushed
already closed

You may meet a longer pattern with Dispose(bool disposing) and a finalizer. It's for classes that hold raw operating-system handles directly, and SafeHandle has replaced most of those. Sealed classes that hold other disposable objects don't need it.

IAsyncDisposable

Some cleanup has to wait, such as flushing a buffer to a network. Dispose can't wait, so blocking in it risks the problems from Day 3. IAsyncDisposable has DisposeAsync, and await using calls it. It also runs on all exit paths, in reverse order.

await using C#
await using (var first = new Sink("first"))
{
    await using var second = new Sink("second");
    await second.WriteAsync("data");
}
Console.WriteLine("after");

class Sink(string name) : IAsyncDisposable
{
    private readonly List<string> pending = new();

    public async Task WriteAsync(string item)
    {
        await Task.Yield();
        pending.Add(item);
    }

    public async ValueTask DisposeAsync()
    {
        await Task.Delay(1);
        Console.WriteLine($"{name} flushed {pending.Count}");
    }
}
Check your prediction
Text
second flushed 1
first flushed 0
after

Disposing in a concurrent world

A background task that outlives its creator can use a resource after it's disposed. So a class that starts work should stop it and wait, before it disposes what that work needs. This shape recurs in real services: signal stop, await the worker, then release. Note how cancellation and DisposeAsync fit together.

Stop, wait, then release C#
await using (var service = new Ticker())
{
    await Task.Delay(30);
}
Console.WriteLine("clean exit");

sealed class Ticker : IAsyncDisposable
{
    private readonly CancellationTokenSource stop = new();
    private readonly Task loop;
    private int ticks;

    public Ticker()
    {
        loop = RunAsync();
    }

    private async Task RunAsync()
    {
        try
        {
            while (true)
            {
                await Task.Delay(5, stop.Token);
                ticks++;
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("loop ended");
        }
    }

    public async ValueTask DisposeAsync()
    {
        stop.Cancel();
        await loop;
        stop.Dispose();
        Console.WriteLine(ticks > 0);
    }
}
Check your prediction
Text
loop ended
True
clean exit

Your turn

Exercise

A batching writer

Write BatchWriter, implementing IAsyncDisposable. It receives a Func<IReadOnlyList<string>, Task> flush and a batchSize. WriteAsync(string item) collects items and flushes a full batch. DisposeAsync flushes anything left, and calling it again after that does nothing and can't repeat a batch. Writing after DisposeAsync has been called throws ObjectDisposedException. A failed flush must keep its items, so that a later flush tries them again. That includes the final one: if DisposeAsync throws, calling it again retries.

Using a fake flush that prints batches, write 5 items with a size of 2 inside an await using. Print end after the block. Then show a second DisposeAsync doing nothing, and a write after disposal being refused. Then, using a fake that fails once, show that its items are flushed the next time. Finally, show a failed DisposeAsync followed by one that succeeds.

When it works, it prints:

Text
a,b
c,d
e
end
refused
disk
x,y
disk full
z
Your workspace C#
await Task.Yield();
Console.WriteLine("Start here");
Hint 1: the idea

The order in flush matters. Clear the buffer only after the flush call has returned, so an exception leaves the items in place.

Hint 2: a first step

Write WriteAsync and a private FlushAsync, which does nothing when the buffer's empty. Then ask what a second DisposeAsync needs to check, given that an empty buffer already makes the flush do nothing.

Show one solution
C#
var writer = new BatchWriter(items =>
{
    Console.WriteLine(string.Join(",", items));
    return Task.CompletedTask;
}, 2);

await using (writer)
{
    foreach (string item in new[] { "a", "b", "c", "d", "e" })
    {
        await writer.WriteAsync(item);
    }
}
Console.WriteLine("end");
await writer.DisposeAsync();

try
{
    await writer.WriteAsync("f");
}
catch (ObjectDisposedException)
{
    Console.WriteLine("refused");
}

bool failNext = true;
var flaky = new BatchWriter(items =>
{
    if (failNext)
    {
        failNext = false;
        throw new IOException("disk");
    }
    Console.WriteLine(string.Join(",", items));
    return Task.CompletedTask;
}, 1);

try
{
    await flaky.WriteAsync("x");
}
catch (IOException e)
{
    Console.WriteLine(e.Message);
}
await flaky.WriteAsync("y");

bool failFinal = true;
var closing = new BatchWriter(items =>
{
    if (failFinal)
    {
        failFinal = false;
        throw new IOException("disk full");
    }
    Console.WriteLine(string.Join(",", items));
    return Task.CompletedTask;
}, 2);

await closing.WriteAsync("z");
try
{
    await closing.DisposeAsync();
}
catch (IOException e)
{
    Console.WriteLine(e.Message);
}
await closing.DisposeAsync();
await closing.DisposeAsync();

sealed class BatchWriter(Func<IReadOnlyList<string>, Task> flush, int batchSize) : IAsyncDisposable
{
    private readonly List<string> buffer = new();
    private bool disposed;

    public async Task WriteAsync(string item)
    {
        ObjectDisposedException.ThrowIf(disposed, this);
        buffer.Add(item);
        if (buffer.Count >= batchSize)
        {
            await FlushAsync();
        }
    }

    private async Task FlushAsync()
    {
        if (buffer.Count > 0)
        {
            // A copy: the callback may keep the batch after this call returns.
            await flush(buffer.ToArray());
            buffer.Clear();
        }
    }

    public async ValueTask DisposeAsync()
    {
        // No early return: if the flush failed, the items are still here to try again.
        // Once they're flushed, the empty buffer makes further calls do nothing.
        disposed = true;
        await FlushAsync();
    }
}
Text
a,b
c,d
e
end
refused
disk
x,y
disk full
z

Two ownership decisions shape this class. The writer owns buffer, so it hands flush a copy (buffer.ToArray()) rather than the list itself. A real flush might queue the batch for an upload and return at once; given the list itself, it would see it emptied by buffer.Clear() a moment later, and the data would be lost without an error. And the buffer is cleared only after flush returns, so a failed flush leaves the items in place for the next attempt. That's also why DisposeAsync has no "already disposed" early return: the empty buffer is what makes a second call do nothing.

Was this article helpful?

Your response is saved on this device.