🔧 Error Fixes
· 1 min read

C#: ObjectDisposedException — How to Fix It


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

  1. Using statement ended — the object was disposed at the end of a using block
  2. Shared HttpClient disposed — one part of code disposed a shared instance
  3. 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