Assume the following code:
using (SqlConnection conn = new SqlConnection(connectionString))
{
...
using (SqlCommand comm = new SqlCommand(...))
{
.. do stuff ..
if(condition) Response.Redirect("somepage.aspx");
}
}
Will the Response.Redirect() exit from the using blocks cause it to dispose all connections?
Or, alternatively, is there any way to exit a using block that won't cause disposal?
EDIT: I don't want to exit without disposal. I want to be aware of any pitfalls that would cause it not to work. -- Barring crashes of course, but then I'm pretty sure all objects are disposed --the hard way-- in that situation
I've accepted an answer, which essentially says "I don't know" but it's a very well researched "I don't know"
For the mean time, I'm going to assume that Response.Redirect aborts the using statement and code with that in mind. -- Until proven otherwise.
From http://msdn.microsoft.com/en-us/library/aa973248.aspx and http://msdn.microsoft.com/en-us/magazine/cc163298.aspx:
Calling Response.Redirect WILL NOT execute the finally block (and language-specific keywords like the C# "using" statement). Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects.
But from http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx:
When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Since the thread can do an unbounded computation in the finally blocks, or call Thread..::.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread..::.Join method. Join is a blocking call that does not return until the thread actually stops executing.
Sounds like a test is in order...
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