πŸ”§ 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.

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

  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);
}

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 await async operations inside using blocks β€” never fire-and-forget a task that depends on a disposable resource.
  • Use IHttpClientFactory instead of manually managing HttpClient lifetimes to avoid both disposal issues and socket exhaustion.

Related: C# cheat sheet Β· C#: HttpClient Timeout fix Β· C#: NullReferenceException fix