ASP.NETexception“线程被中止”导致方法退出
在下面的代码中,someFunctionCall()有时会生成“Thread is aborted”exception。 为什么代码块B中的代码永远不会运行? ASP.NET是否为每个方法调用启动一个新线程? 我很惊讶地看到,当发生此exception时,块b中的代码永远不会运行,该方法返回,并且我的应用程序继续运行。 有人可以解释一下吗?
谢谢。
public void method() { // CODE BLOCK A //... try { someFunctionCall(); // this call is generating thread abort exception } catch(Exception ex) { // log exception message } // CODE BLOCK B // ... }
这是一个ThreadAbortException
; 它是一个特殊的exception,它会在每个catch块的末尾自动重新抛出,除非你调用Thread.ResetAbort()
。
像Response.End
或Response.Redirect
这样的ASP .Net方法(除非你传递false
)将此exception抛给当前页面的结束处理; 你的someFunctionCall()
可能正在调用其中一种方法。
ASP .Net本身处理此exception并调用ResetAbort
继续处理。
若要解决此问题,请使用下列方法之一:对于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
方法。
试试这种方式:
这是我的扩展方法:
public static void WriteJSONObject(this HttpResponse response, object content) { response.ContentType = "application/json"; response.Write(new JavaScriptSerializer().Serialize(content)); response.End(); }
逻辑:
public void RegisterUser() { try { Response.WriteJSONObject(new { Result = "See hello" }); } catch (Exception err) { if (err.Message != "Thread was being aborted.") Response.WriteJSONObject(new { Result = err.Message }); else { Response.End(); } } }