ASP.NET例外"正在中止线程"导致方法退出线程、方法、ASP、NET

2023-09-02 23:53:23 作者:吻痕

在下面的code,有时someFunctionCall()生成一个线程已被中止的异常。为什么在code code块B从不运行? ASP.NET是否开始为每个方法调用一个新的线程?我很惊讶地看到,当这个例外发生在code在B座从来没有运行,该方法返回,和我的应用程序保持运行。有人可以解释一下吗?

感谢。

 公共无效的方法()
{
   // code座一
   // ...


   尝试
   {
       someFunctionCall(); //这个调用产生线程中止异常
   }
   赶上(例外前)
   {
      //日志异常消息
   }

  // code B座
  // ...

}
 

解决方案 JVM 如何分析线程堆栈

这是一个 ThreadAbortException ;这是一个特殊的例外,即在每一个catch块结束时会自动重新抛出,除非你叫 Thread.ResetAbort()

ASP.NET的方法,如到Response.End 的Response.Redirect (除非你通过)抛出此异常来结束当前页的处理;你的 someFunctionCall()可能是调用这些方法之一。

ASP.NET的自己处理这个异常并调用 ResetAbort 继续处理。

In the code below, sometimes someFunctionCall() generates a "Thread was being aborted" exception. How come the code in code block B never runs? Does ASP.NET start a new thread for each method call? I was suprised to see that when this exception happens the code in block b never runs, the method returns, and my application keeps running. Can someone please explain this?

Thanks.

public void method()
{
   // CODE BLOCK A
   //...


   try 
   {
       someFunctionCall(); // this call is generating thread abort exception
   }
   catch(Exception ex)
   {
      // log exception message
   }

  // CODE BLOCK B
  // ...

}

解决方案

This is a ThreadAbortException; it's a special exception that is automatically rethrown at the end of every catch block, unless you call Thread.ResetAbort().

ASP .Net methods like Response.End or Response.Redirect (unless you pass false) throw this exception to end processing of the current page; your someFunctionCall() is probably calling one of those methods.

ASP .Net itself handles this exception and calls ResetAbort to continue processing.