wasAsked.

using (SqlConnection con = new SqlConnection(...)) — what does using actually do? - Follow-up: IDisposable vs garbage collector — what's the difference?

Routeware · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

What "using" does The using statement guarantees that Dispose() is called on the object when the block ends — whether normally, by return, or because of an exception. The compiler turns it into a try/finally: SqlConnection con = new SqlConnection(connectionString); try { con.Open(); // execute commands } finally { con?.Dispose(); // also closes the connection } For SqlConnection, Dispose closes the connection and returns the underlying physical connection to the connection pool, so another request can reuse it immediately. Without it, connections stay open until the garbage collector eventually finalises the objects, and under load the pool runs out ("Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool"). Modern syntax: using var con = new SqlConnection(connectionString); // disposed at end of scope await using var reader = await cmd.ExecuteReaderAsync(ct); // async disposal Follow-up: IDisposable vs garbage collector Garbage collector - Manages memory only: reclaims managed objects that are no longer reachable. - Runs at unpredictable times, decided by the runtime. - Does not know about the scarcity of external resources such as connections, file handles or sockets. IDisposable - A pattern for deterministic cleanup of resources: you decide exactly when the resource is released. - Used for unmanaged or limited resources: database connections, files, network streams, timers, native handles, and objects that wrap them. - Dispose releases the resource; the object's memory is still reclaimed later by the GC. How they relate - A class holding unmanaged resources can also have a finalizer as a safety net, which the GC calls if Dispose was forgotten. Dispose calls GC.SuppressFinalize(this) so the finalizer is skipped, making cleanup cheaper. - Relying on finalizers is slow and unpredictable, so always dispose explicitly. Rule of thumb - If you create an object that implements IDisposable and you own it, wrap it in using or await using. - Do not dispose objects owned by someone else, such as services injected by dependency injection or pooled HttpClient instances from IHttpClientFactory.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics