English 中文(简体)
Context.Response.End()和线程被中止。
原标题:Context.Response.End() and Thread was being aborted
  • 时间:2010-03-04 09:50:40
  •  标签:
  • asp.net

我正在尝试使用 Context.Response.End 来关闭响应,但收到错误 "线程被中止"

我如何正确关闭响应,而不触发异常?

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) {
}
问题回答

是否有具体理由使用<条形码>。

这种方法将短路 ASP.NET 管道(除了 EndRequest 事件)而不会抛出 ThreadAbortException,因此您不需要额外的 try/catch 块,而且您也会获得更好的性能。

Try response.OutputStream.Close(); instead of response.End(); It will help!

错误:线程被中止。在System.Threading.Thread.Ab或者tInternal()中,在System.Threading.Thread.Ab或者t(Object stateInfo)中,在System.Web.HttpResponse.End()中。

这一错误主要发生在你使用对应措施时。 最后,答复。 转机

原因:反应。 最终方法结束页执行,并将执行改为申请。 申请启动过程中的终止活动。 接下来是反应。 最终未执行。

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

解决方案 (jiě jué fāng àn)

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

或者

F或者 Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event. F或者 Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false f或者 the endResponse parameter to suppress the internal call to Response.End. F或者 example: ex: Response.Redirect (“nextpage.aspx”, false); If you use this w或者karound, the code that follows Response.Redirect is executed. F或者 Server.Transfer, use the Server.Execute method instead.

我推荐这个解决方案:

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

  2. 声明这个全局变量:bool isFileDownLoad; Note: This translation is in Simplified Chinese.

  3. 仅仅在您(答复:Write(sw.ToString());)之后,即=>是FileDownLoad = 真实;

  4. 覆盖你的渲染,如下:

    /// /// AEG : Very important to handle the thread aborted exception /// /// override protected void Render(HtmlTextWriter w) { if (!isFileDownLoad) base.Render(w); }

或者你可以把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();
}

这帮助我处理了“线程被中止”的异常。

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

如果您使用以下代码而不是<代码> 页: 1 服务器在发送例外之后不能贴上头盔。

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

希望有所帮助。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签