IDisposable is an interface with a single method, Dispose(), used to release resources deterministically — at a known moment — instead of waiting for the garbage collector. The using statement guarantees Dispose is called. Why it is needed The GC manages memory, but not other resources: database connections, file handles, network sockets, streams, timers, native memory, or locks. Waiting for the GC (or a finalizer) to release them can exhaust connection pools, keep files locked or leak OS handles. using statement using (var stream = File.OpenRead(path)) { // read } // stream.Dispose() is called here, even if an exception is thrown Modern using declaration (C# 8), disposed at the end of the enclosing scope: using var connection = new SqlConnection(connectionString); await connection.OpenAsync(ct); Async disposal for resources with async cleanup (IAsyncDisposable): await using var writer = new StreamWriter(path); await writer.WriteLineAsync("data"); The compiler turns using into a try/finally block that calls Dispose. When to use it - Any object implementing IDisposable that you create and own: SqlConnection, DbContext created manually, FileStream, StreamReader, HttpResponseMessage, CancellationTokenSource, Timer, SemaphoreSlim. - Do not dispose objects you do not own — for example services injected by the DI container (the container disposes them) or HttpClient instances from IHttpClientFactory. Implementing IDisposable in your own class Implement it when your class owns disposable fields or unmanaged resources: public sealed class ReportExporter : IDisposable { private readonly FileStream _file; private bool _disposed; public ReportExporter(string path) => _file = File.Create(path); public void Dispose() { if (_disposed) return; _file.Dispose(); _disposed = true; } } For classes that directly own unmanaged handles, use SafeHandle or the full Dispose pattern with a finalizer and GC.SuppressFinalize(this). Common mistakes - Forgetting to dispose, causing connection-pool exhaustion ("Timeout expired... max pool size was reached"). - Creating new HttpClient instances per request and disposing them, which can exhaust sockets — use IHttpClientFactory instead. - Using an object after disposing it (ObjectDisposedException).
Ravindra Wadile · · 0 likes