In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using
statement?
using (var conn = new SqlConnection("...")) { conn.Open(); // stuff happens here and exception is thrown... }
I know this code below will make sure that it does, but I'm curious how using statement does it.
var conn; try { conn = new SqlConnection("..."); conn.Open(); // stuff happens here and exception is thrown... } // catch it or let it bubble up finally { conn.Dispose(); }
Using-blocks are convenient way to automatically dispose objects that implement IDisposable interface to release resources that garbage collection cannot automatically manage.
The exception is thrown, because there is no catch statement in the compiled code. If you handle the exception within the using block, your object will still be disposed in the compiler-generated finally block.
// If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. private void Dispose(bool disposing) { // Check to see if Dispose has already been called.
The using declaration calls the Dispose method on the object in the correct way when it goes out of scope. The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned.
Yes, using
wraps your code in a try/finally block where the finally
portion will call Dispose()
if it exists. It won't, however, call Close()
directly as it only checks for the IDisposable
interface being implemented and hence the Dispose()
method.
See also:
This is how reflector decodes the IL generated by your code:
private static void Main(string[] args) { SqlConnection conn = new SqlConnection("..."); try { conn.Open(); DoStuff(); } finally { if (conn != null) { conn.Dispose(); } } }
So the answer is yes, it will close the connection if
DoStuff()throws an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With