【问题标题】:Context.Response.End() and Thread was being abortedContext.Response.End() 和线程被中止
【发布时间】:2010-03-04 09:50:40
【问题描述】:

我正在尝试使用 Context.Response.End 关闭响应,但收到错误 "Thread was being aborted"

如何在不触发异常的情况下正确关闭响应?

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) {

}

自己解决了,代码应该是这样的

try {
  Context.Response.End();
} catch (ThreadAbortException err) {

}
catch (Exception err) {
}

【问题讨论】:

  • 你在 try catch 块中有 respose.end 吗?
  • 我已经添加了我的代码。是的,我添加了 Context.Response.End();在 Try/catch 块内,如您所见,有一个主要的 Try/catch 块,它也是捕获错误“线程被中止”。
  • 自己解决了,代码应该是这样的 try { } catch (ThreadAbortException err) { } catch (Exception err) { }

标签: asp.net


【解决方案1】:

您没有使用context.ApplicationInstance.CompleteRequest() 是否有特定原因?

此方法将短路 ASP.NET 管道(EndRequest 事件除外)而不抛出 ThreadAbortException,因此您不需要额外的 try/catch 块,您还将体验到更好的性能.

【讨论】:

  • 我刚试过这个(派对有点晚了)。它似乎不能正常工作:当然它没有抛出异常 Response.End() 抛出,但它确实导致 .aspx 页面的内容被附加到我已经写入 Response.OutputStream 的内容中.一种选择可能是在 .aspx 文件中没有内容,但我已经使用它来显示错误内容。
【解决方案2】:

尝试 response.OutputStream.Close(); 而不是 response.End(); 会有帮助的!

【讨论】:

  • 为我工作!谢谢!
【解决方案3】:

错误:线程被中止。在 System.Threading.Thread.AbortInternal() 在 System.Threading.Thread.Abort(Object stateInfo) 在 System.Web.HttpResponse.End()

此错误主要发生在使用 Response.End、Response.Redirect 或 Server.Transfer 时

原因:Response.End 方法结束页面执行并将执行转移到应用程序事件管道中的 Application_EndRequest 事件。 Response.End 后面的代码行没有被执行。

这个问题出现在 Response.Redirect 和 Server.Transfer 方法中,因为这两个方法都在内部调用了 Response.End。

解决方案/解决方案:

您可以使用 try-catch 语句来捕获此异常

对于 Response.End,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 方法而不是 Response.End 以绕过代码执行到 Application_EndRequest 事件。对于 Response.Redirect,使用重载 Response.Redirect(String url, bool endResponse) 为 endResponse 参数传递 false 以抑制对 Response.End 的内部调用。例如:例如:Response.Redirect(“nextpage.aspx”, false);如果您使用此解决方法,将执行 Response.Redirect 之后的代码。对于 Server.Transfer,请改用 Server.Execute 方法。

【讨论】:

    【解决方案4】:

    我推荐这个解决方案:

    1. 不要使用 response.End();

    2. 声明这个全局变量:bool isFileDownLoad;

    3. 就在您的 (response.Write(sw.ToString());) 设置 ==> isFileDownLoad = true; 之后

    4. 像这样覆盖你的渲染:

      /// /// AEG : 处理线程中止异常非常重要 /// /// 覆盖受保护的无效渲染(HtmlTextWriter w) { if (!isFileDownLoad) base.Render(w); }

    【讨论】:

      【解决方案5】:

      或者您可以将 context.Response.End() 放在 finally 块中。这样您就不必关心不需要的 ThreadAbortException,也不必忽略真正的 ThreadAbortException(这很糟糕)。您也不会忽略管道阶段。

      try
      {
          context.Response.ContentType = "application/json";
          context.Response.ContentEncoding = Encoding.UTF8;
      
          if (NotAuthorized())
          {
              context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
              return;
          }
      
          context.Response.Write(MakeJsonStuff());
      }
      catch (Exception ex)
      {
          LogException(ex);
      
          context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
          context.Response.Write(MakeJsonError(ex));
      }
      finally
      {
          context.Response.End();
      }
      

      【讨论】:

        【解决方案6】:

        这有助于我处理Thread was being aborted 异常,

        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);
             }
           }
        

        如果您使用以下代码而不是 HttpContext.Current.Response.End() ,您将得到 Server cannot append header after HTTP headers have been sent 异常。

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

        我发现的另一个修复是Thread.BeginCriticalRegion();

           try 
         {
            //Write HTTP output
           HttpContext.Current.Response.Write(Data);
          } catch (Exception exc) {} 
          finally {
            try {
             //Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
             Thread.BeginCriticalRegion();
             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();
            Thread.EndCriticalRegion();
                 }
           }
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 2012-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-17
          • 2011-09-26
          • 1970-01-01
          • 2011-06-12
          • 1970-01-01
          相关资源
          最近更新 更多