由Response.Redirect引发的"Thread was being aborted. "异常

Abort一定会抛出ThreadAbortException异常

ThreadAbortException   类  
  在对   Abort   方法进行调用时引发的异常。无法继承此类。  
  备注  
  在调用   Abort   方法以销毁线程时,公共语言运行库将引发   ThreadAbortException。ThreadAbortException   是一种可捕获的特殊异常,但在   catch   块的结尾处它将自动被再次引发。引发此异常时,运行库将在取消线程前执行所有   finally   块。由于线程可以在   finally   块中进行未绑定的计算,因此必须调用   Join   方法以保证线程已死亡。Join   是一个阻塞调用,它要到线程实际停止执行后才返回。  
   
  ThreadAbortException   使用值为   0x80131530   的   HRESULT   COR_E_THREADABORTED。  

将Response.Redirect写入try...catch会出现异常

try 

    Response.Redirect(
"Index.aspx"); 

catch(Exception e) 

    Response.Redirect(
"Error.aspx?message=" + e.Message); 

如上,则会显示"Thread was being aborted. "异常

同样的还有Response.End()等提前结束当前Theard的方法

解决方案一:

如果 Response.Redirect("Index.aspx"); 必须写到Try{}里,则可以在Catch语句写入:

catch(Exception e) 

    
if (!(e is ThreadAbortException)) 
    { 
        Response.Redirect(
"Error.aspx?message=" + e.Message); 
    } 
}
  略过系统对这个特殊异常的处理。

 解决方案二:

MSDN已经解析清楚了
“调用 Redirect 等效于在将第二个参数设置为 true 的情况下调用 Redirect。 Redirect 调用 End,它在完成时引发 ThreadAbortException 异常。” 可见Redirect方法在内部是调用 Thread.Abort()来中止线程的从而引发ThreadAbortException 异常。如果不想立刻中止则,第二个参数设置为false

C# code

protected void Button1_Click(object sender, EventArgs e)
{
try
{
Response.Redirect(
"A.aspx",false);
}
catch( Exception e1)
{
Response.Redirect(
"B.aspx");
}
}
对于 Server.Transfer,请改用 Server.Execute 方法。  
原文地址:https://www.cnblogs.com/cuihongyu3503319/p/1353462.html