Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.Redirect("") inside "using{ }"

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.

like image 769
Chris Cudmore Avatar asked Dec 18 '22 10:12

Chris Cudmore


1 Answers

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...

like image 176
Even Mien Avatar answered Jan 03 '23 06:01

Even Mien