线程已被中止错误(Thread was being aborted.)

在捕获异常的try块中使用
Response.Redirect(....);

Response.Write(....);
Response.End();

有时会提示线程已被中止错误;(该错误不会每次都产生,在相同地方只是偶尔会出现)

System.Threading.ThreadAbortException: Thread was being aborted.
at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo)
at System.Web.HttpResponse.End()


分析该错误的原因是由于执行这两个命令会重新发起一次请求,将当前请求的进程Abort掉。

通俗点讲就是当进程还想继续执行的时候, 发现自己已经被调用过Abort方法了。既然自己作为线程已经被中止, 就无法执行了, 于是Exception丢了出来。
解决方法有如下三种:
1、将这两个命令放到try/catch块外,不捕获异常就不会提示这个错误;
2、捕获异常时进行判断:

try
{ 
    // 一些操作
}
catch (Exception ex)
{
    if (!(ex is System.Threading.ThreadAbortException))
    {
        // 在这里显示错误
    }
}


3、捕获进程终止错误不做处理

try
{
    // 一些操作
}
catch (System.Threading.ThreadAbortException)
{ 
                
}
catch (Exception ex)
{
    //显示错误
}

 

posted @ 2014-02-24 16:23  bsso  阅读(1287)  评论(0)    收藏  举报
土蜀佃博客