Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
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.