DEV Community

Cover image for C# Tip: Asynchronous Disposable
Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Asynchronous Disposable

Let’s talk about Asynchronous Disposable, introduced in C# 8, which allows you to release resources asynchronously, useful in scenarios where releasing resources may take time. This is particularly important in applications that handle resources such as database connections, files, or network streams, which often need to be closed properly. See the example in the code below.

using System;
using System.IO;
using System.Threading.Tasks;

public class AsyncFile : IAsyncDisposable
{
    private readonly FileStream _fileStream;

    public AsyncFile(string path)
    {
        _fileStream = new FileStream(path, FileMode.OpenOrCreate);
    }

    public async Task WriteAsync(string content)
    {
        byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
        await _fileStream.WriteAsync(data, 0, data.Length);
    }

    public async ValueTask DisposeAsync()
    {
        await _fileStream.DisposeAsync(); // Asynchronously releasing the resources
    }
}

public class Program
{
    public static async Task Main()
    {
        // Using "await using" to ensure resources are released asynchronously
        await using (var file = new AsyncFile("file.txt"))
        {
            await file.WriteAsync("Asynchronous content");
        }
        // Resources are asynchronously released here without blocking the rest of the code
        Console.WriteLine("File written and resources released.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
In modern applications, we often work with resources that need to be released once the work is done. Traditionally, we use the IDisposable interface to release these resources synchronously, which is efficient for quick operations. However, in scenarios where releasing resources can take time, such as closing network connections or writing large amounts of data to a file, synchronous disposal can block the application, affecting performance.

This is where Asynchronous Disposable comes in, allowing you to release these resources asynchronously. By implementing the IAsyncDisposable interface, you can release resources without blocking the rest of the application. This is perfect for scenarios where there are operations that take time to complete, such as writing to large files or closing network or database connections.

In the example above, we show how to create a class that writes to a file asynchronously and releases resources using DisposeAsync.

Source code: GitHub

I hope this tip helps you! Until next time.

Top comments (0)