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) { }
CompleteRequest Instead of Response. End.
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.
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.
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