asp.net出现正在中止线程解决方案

刚才又再次遇到了一个之前遇到的问题,在这里记录一下。

起因:

如果使用 Response.End、Response.Redirect 或 Server.Transfer 方法,将出现 ThreadAbortException 异常。您可以使用 try-catch 语句捕获此异常。

原因:

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

Response.End 方法终止页的执行,并将此执行切换到应用程序的事件管线中的 Application_EndRequest 事件。不执行 Response.End 后面的代码行,所以导致了这个问题。

解决方案:

1.对于Response.End,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 方法而不是 Response.End 以跳过 Application_EndRequest 事件的代码执行。

2.对于Response.Redirect,请使用重载Response.Redirect(String url, bool endResponse),endResponse 参数传递 false 以取消对 Response.End 的内部调用。