Monday, August 30, 2010

response.End v/s response.Flush

So, I was writing this class to export my Datatable into a xls spreadsheet. Pretty straightforward code with no fancy bells or whistles when suddenly .NET started throwing the following exception:


IP= , xxx.xxx.xxx.xxx
SOURCE - mscorlib
TARGET SITE - Void AbortInternal()
MESSAGE - Thread was being aborted.
BASE ERROR SOURCE = mscorlib
INNER EXCEPTION =
EXCEPTION DATA = System.Collections.ListDictionaryInternal+NodeKeyValueCollection
STACK TRACE = at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo)
at System.Web.HttpResponse.End()
at ExportData.ExportDetails(DataTable DetailsTable, ExportFormat FormatType, String filename)
at xxx_Search_xxx.getcsv(Object o, EventArgs e)
TARGET SITE = Void AbortInternal()
############################################


I was pretty baffled for a while and kept debating if this was normal behavior and if it is possible to gracefully abort instead of (what looks like) a sudden abrupt abort

Yes, this is indeed by design. Microsoft has even documented it. 



There is no such thing as a "graceful" abort. You could simply Flush() the response, though, instead of ending it and let the framework take care of closing the connection for you. I'm assuming in this case that you want the response sent to the client, i.e., the typical case.
According to MSDN, calling Response.End() throws the ThreadAbortException when the response ends prematurely. You really should only call Response.End() when you want the exception raised. Else always Response.Flush();


1 comment:

All Blond said...

End if I have only response.flush() on my web app and getting exact same error as you with response.end()?
Any other bright ideas what could be cost of this misbehavior, beside Microsoft usual...