Error: [System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

When trying to download a file using similar code to the below, I kept on getting the ThreadAbortException:

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader(“content-disposition”, attachment);
HttpContext.Current.Response.ContentType = “text/csv”;
HttpContext.Current.Response.AddHeader(“Pragma”, “public”);

var sb = new StringBuilder();

foreach (string row in rows)
{
sb.Append(row + “\r\n”);
}

HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();

Even if I surround it with try and catch, I was not solving my issue since I simply do not want the exception to occur and not go around it. After some research I discovered that reason was that Response.End ends the whole page execution and fires the Application_EndRequest event. Cutting the story short, replacing Response.End with the below solved my issue since it does not fire the Application_EndRequest event and continues to execute my page:

HttpContext.Current.ApplicationInstance.CompleteRequest();