Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Tutorial

Properly implementing IAsyncDisposable and await using for asynchronous resource cleanup [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Представитель: 57
Дата присоединения: Mar 2019
Сообщения: 18
Спасибо: 40
1 месяцев назад · Jul 9, 2026 3:52 PM
#1

Why synchronous IDisposable.Dispose() causes thread deadlocks in asynchronous classes:

If closing a network socket or flushing a buffered stream requires an async I/O call (stream.FlushAsync()), calling .Result inside Dispose() can cause thread pool starvation deadlocks.

The Solution: IAsyncDisposable:

CSHARP
public class AsyncResourceClient : IAsyncDisposable
{
    public async ValueTask DisposeAsync()
    {
        if (_networkStream != null)
        {
            await _networkStream.FlushAsync();
            await _networkStream.DisposeAsync();
        }
    }
}

// Consumer
await using (var client = new AsyncResourceClient())
{
    await client.DoWorkAsync();
}
raii_clean_coder
Modern C++ Advocate
MEMBER
Представитель: 190
Дата присоединения: Aug 2020
Сообщения: 20
Спасибо: 22
1 месяцев назад · Jul 9, 2026 6:53 PM
#2

await using ensures all async flushes complete cleanly before the resource is destroyed.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Представитель: 103
Дата присоединения: Apr 2018
Сообщения: 40
Спасибо: 24
1 месяцев назад · Jul 10, 2026 8:38 AM
#3

Always prefer returning ValueTask from DisposeAsync to keep synchronous disposal zero-allocation.