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.
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);
}
Related: C# cheat sheet · C#: HttpClient Timeout fix · C#: NullReferenceException fix