ObjectDisposedException: Cannot access a disposed object means youβre trying to use an object (usually a stream, connection, or HttpClient) after itβs been disposed.
Why this happens
In C#, the using statement automatically calls Dispose() on an object when execution leaves the block. If an async operation is still running when the block ends, or if multiple parts of your code share the same disposable instance, the object gets disposed while something is still trying to use it. This is especially common with HttpClient, database connections, and streams in async code.
What causes this error
- Using statement ended β the object was disposed at the end of a
usingblock - Shared HttpClient disposed β one part of code disposed a shared instance
- Async timing β an async operation completes after the object is disposed
Fix 1: Extend the using scope
// β Stream disposed before async operation completes
using (var stream = new MemoryStream()) {
_ = ProcessAsync(stream);
} // stream disposed here
// β
Await inside the using block
using (var stream = new MemoryStream()) {
await ProcessAsync(stream);
}
Fix 2: Donβt dispose shared HttpClient
// β Creating and disposing HttpClient per request
using var client = new HttpClient();
// β
Use IHttpClientFactory (ASP.NET Core)
// Or create a single static instance
private static readonly HttpClient _client = new HttpClient();
Fix 3: Check if disposed before using
if (!connection.State == ConnectionState.Closed) {
await connection.ExecuteAsync(query);
}
Alternative solutions
Use the await using syntax (C# 8+) for async disposables to ensure proper cleanup timing:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await connection.ExecuteAsync(query);
Prevention
- Always
awaitasync operations insideusingblocks β never fire-and-forget a task that depends on a disposable resource. - Use
IHttpClientFactoryinstead of manually managingHttpClientlifetimes to avoid both disposal issues and socket exhaustion.
Related: C# cheat sheet Β· C#: HttpClient Timeout fix Β· C#: NullReferenceException fix