How to Avoid Response.End() “Thread was being aborted” Exception during the Excel file download

后端 未结 16 2129
感动是毒
感动是毒 2020-11-27 11:47

I tried to convert my dataset into excel and download that excel .I got my required excel file.But System.Threading.ThreadAbortException was raised every excel download. Ho

相关标签:
16条回答
  • 2020-11-27 12:13

    Move the Response.End() to outside of the Try/Catch and Using blocks.

    It's suppose to throw an Exception to bypass the rest of the request, you just weren't suppose to catch it.

    bool endRequest = false;
    
    try
    {
        .. do stuff
        endRequest = true;
    }
    catch {}
    
    if (endRequest)
        Resonse.End();
    
    0 讨论(0)
  • 2020-11-27 12:14

    This helped me to handle Thread was being aborted exception,

    try
    {
       //Write HTTP output
        HttpContext.Current.Response.Write(Data);
    }  
    catch (Exception exc) {}
    finally {
       try 
        {
          //stop processing the script and return the current result
          HttpContext.Current.Response.End();
         } 
       catch (Exception ex) {} 
       finally {
            //Sends the response buffer
            HttpContext.Current.Response.Flush();
            // Prevents any other content from being sent to the browser
            HttpContext.Current.Response.SuppressContent = true;
            //Directs the thread to finish, bypassing additional processing
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            //Suspends the current thread
            Thread.Sleep(1);
         }
       }
    

    if you use the following the following code instead of HttpContext.Current.Response.End() , you will get Server cannot append header after HTTP headers have been sent exception.

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

    Hope it helps

    0 讨论(0)
  • 2020-11-27 12:14

    I found that the following worked better...

       private void EndResponse()
        {
            try
            {
                Context.Response.End();
            }
            catch (System.Threading.ThreadAbortException err)
            {
                System.Threading.Thread.ResetAbort();
            }
            catch (Exception err)
            {
            }
        }
    
    0 讨论(0)
  • 2020-11-27 12:15

    I found the reason. If you remove update panels it woks fine!

    0 讨论(0)
  • 2020-11-27 12:18

    flush the response to the client before response.end()

    More about Response.Flush Method

    So use the below-mentioned code before response.End();

    response.Flush();  
    
    0 讨论(0)
  • 2020-11-27 12:22

    I removed the linkbutton from the UpdatePanel and also commented the Response.End() Success!!!

    0 讨论(0)
提交回复
热议问题