繁体   English   中英

C#thread中止异常

[英]C# thread abort exception

在thread.Abort()之后会发生什么?

说我有:

Thread mWorker = new Thread(new ThreadStart(this.run));
..
mWorker.Start();

**where**

private void run() 
{
      Logger.d(TAG, "run()");

      ...
      try {
        while (this.mRunning){
          ...
        }
      } catch (ThreadAbortException tae){
           Logger.e(TAG,"some msg", tae);
           this.doSomething();
      } catch (IOException ioe){
           Logger.e(TAG,"some msg", ioe);
           this.doSomething();
      } catch (Exception e){
           Logger.e(TAG,"some msg", e);
           this.doSomething();
      } finally {
            gracefoulyClose();
      }

      Logger.d(TAG, "run() - ended");
}

线程更复杂..但这里显示的是必要的。 那么当Abort()被调用时会发生什么? 我的捕获工作会继续doSomething()的调用吗?

因为我还在控制台收到:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code

但我确实有一个问题。 不是吗?

来自doc

当调用Abort方法来销毁线程时,公共语言运行库会抛出ThreadAbortException。 ThreadAbortException是一个可以捕获的特殊异常,但它会在catch块的末尾自动再次引发 引发此异常运行时会在结束线程之前执行所有finally块 因为线程可以在finally块中执行无限制计算或调用Thread.ResetAbort来取消中止,所以无法保证线程将永远结束。 如果要等到中止的线程结束,可以调用Thread.Join方法。 Join是一个阻塞调用,在线程实际停止执行之前不会返回。

换句话说,在执行ThreadAbortException catch块之后,会重新引发异常,因此您的最后一个记录器行(例如Logger.d(TAG, "run() - ended") )永远不会执行。 但由于呼叫this.doSoemthing是对catch块ThreadAbortException它将执行。

另请注意,您的finally确实执行(请参阅上面的doc)。

如果您在代码response.redirect();中使用某些位置response.redirect(); 那么它将在内部运行thread.abort(); 所以它会抛出异常。相反,你可以使用Response.Redirect(url,false);

您收到ThreadAbortException,因为在线程完成运行之前您的上下文正在退出。 在退出之前,您需要等待线程完成。 如果要退出,则需要确保线程可以接收程序希望结束的信号(并对其执行操作),然后管理程序执行的代码必须等待线程完成:

if (mThread != null && mThread.IsAlive) {
    mThread.Join();
}

如果您担心线程永不退出,请使用带超时的重载,如果您点击计时器,则显式终止该线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM