Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context.Response.End() and Thread was being aborted

Tags:

asp.net

I am trying to close the response using Context.Response.End but receive error "Thread was being aborted".

How do I correctly close the response without triggering an exception?

try {    Context.Response.Clear();    Context.Response.ContentType = "text/html";     //Context.Response.ContentType = "application/json";    JsonObjectCollection collection = new JsonObjectCollection();    collection.Add(new JsonNumericValue("resultcode", 1));    collection.Add(new JsonStringValue("sourceurl", exchangeData.cUrl));    collection.Add(new JsonStringValue("filename", fileName));    collection.Add(new JsonStringValue("filesize", fileSize));    collection.Add(new JsonStringValue("fileurl", Common.GetPDFURL + outputFileName));    JsonUtility.GenerateIndentedJsonText = true;    Context.Response.Write(collection);   try {      Context.Response.End();   } catch (ThreadAbortException exc) {      // This should be first catch block i.e. before generic Exception      // This Catch block is to absorb exception thrown by Response.End   } } catch (Exception err) {  } 

Solved by myself, the code should look like

try {   Context.Response.End(); } catch (ThreadAbortException err) {  } catch (Exception err) { } 
like image 351
Tomas Avatar asked Mar 04 '10 09:03

Tomas


People also ask

What can I use instead of response end?

CompleteRequest Instead of Response. End.

What is thread being aborted?

If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur. If Abort is called on a thread that has not been started, the thread will abort when Start is called. If Abort is called on a thread that is blocked or is sleeping, the thread is interrupted and then aborted.


1 Answers

Is there a specific reason you aren't using context.ApplicationInstance.CompleteRequest() instead?

This method will short circuit the ASP.NET pipeline (except for the EndRequest event) without throwing the ThreadAbortException so you won't need the extra try/catch block, and you will also experience better performance.

like image 125
John Rasch Avatar answered Oct 16 '22 10:10

John Rasch