Skip to content

EN CSharp Resources

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Release resources: IDisposable, using and await using

Manual C# · Examples UO

IDisposable.Dispose releases a resource when it is no longer needed. using associates the release with the code area; await using is waiting for IAsyncDisposable.DisposeAsync. The garbage collector frees managed memory and is not a substitute for closing files and other external resources in a timely manner.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
using System;
using (var stream = new System.IO.MemoryStream())
{
    stream.WriteByte(65);
    Console.WriteLine(stream.Length);
}

Result:

1
{
    using var stream = new System.IO.MemoryStream();
    stream.WriteByte(42);
    stream.Position = 0;
    UO.Print(stream.ReadByte().ToString());
}
sealed class Lease : IAsyncDisposable
{
    public bool Released { get; private set; }
    public ValueTask DisposeAsync()
    {
        Released = true;
        return ValueTask.CompletedTask;
    }
}

var lease = new Lease();
await using (lease)
{
    await WaitAsync(10);
}
UO.Print(lease.Released.ToString());

Official documentation: Release resources: IDisposable, using and await using - Microsoft Learn.

Clone this wiki locally