Tuesday, February 7, 2017

System.Threading.ThreadAbortException: Thread was being aborted.

I have a DataTable which is bound to a Grid View. I also have a button that when clicked exports the DataTable to an Excel file. However, the following error is occurring:

ErrorMsg = "Thread was being aborted."

Here is part of the code where the error is being thrown:


    private void ExportToExcel()
    {
        try
        {
            DataTable dt = (DataTable)ViewState["dtSearchPropertyData"];
            if (dt != null && dt.Rows.Count > 0)
            {
                GridView _gv = new GridView();
                _gv.DataSource = dt;
                _gv.DataBind();
                string attachment = "attachment; filename=Data.xls";
                Response.Clear();
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                Response.ContentType = "application/vnd.ms-excel";
                using (System.IO.StringWriter sw = new System.IO.StringWriter())
                {
                    System.Web.UI.HtmlTextWriter htmltextwriter = new System.Web.UI.HtmlTextWriter(sw);
                    _gv.AllowPaging = false;

                    _gv.RenderControl(htmltextwriter);
                    Response.Output.Write(sw.ToString());
                    Response.Flush();
                    Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            throw(ex);
        }
    }

Here The ThreadAbortException is thrown from the following line:

                    Response.End();

To resolve this :

/*Replace code */
                    Response.Flush();
                    Response.End();


/*With below line*/

                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.SuppressContent = true;
                        HttpContext.Current.ApplicationInstance.CompleteRequest(); 

Now this is working fine.