Thursday, November 1, 2007

Server.Transfer / Response.Redirect Bug

One fine day I got an error in code "Thread abort exception", where as I was not using any threading code but simply using Response.Redirect. After doing lot of study/Research found solution that, Response.Redirect works on browser only.. That it sends request to browser to change the page. ** 2 round trips are required**.
Here the above error comes because the thread in which your pageone.aspx is executing breaks when Response.Redirect is encountered.

Optimized Solution : - See the second parameter with Response.Redirect ("something.aspx",EndResponse), Here if you write ("something.aspx",False) you are going to land in trouble. So better to use ("something.aspx",True) i.e redirect to given page and end the current thread.

Raw Solution :- Generally developers think that writting try-catch block for every error is good practice. But this is not the real world solution, you should try to avoid the unnecessary try-catch block coz using try-catch excessively is also a performance penalty..

If you go the "Thread Abort Exception" don't use the below code

Try
Response.Redirect("destination.aspx")
Catch ex as threadabortexception
'leave it blank
end try
A good solution to this issue is use response.redirect("page name",false).The second parameter is "Endresponse" so set value to false.


The next is Sever.Transfer.... Some time this also fires the above "Thread Abort Exception" so either change Server.Transfer with Response.Redirect or set the second parameter of Server.Transfer to False (Server.Transfer("destination.aspx",false))

No comments: