ThreadAbortException

前端 未结 4 405
孤城傲影
孤城傲影 2020-12-08 01:47

Let\'s say we have some code like this running in the separate thread:

private static void ThreadFunc() {
    ulong counter = 0;

    while (true) {

                


        
4条回答
  •  囚心锁ツ
    2020-12-08 02:37

    Actually, ThreadAbortException is special in case it's thrown by CLR or Thread.Abort method. Compare output:

    • Slightly modified example (added Console.WriteLine) from Joe Duffy's "Concurrent Programming on Windows". It throws the exception by Thread.CurrentThread.Abort:
      
      try
      {
          try
          {
              Thread.CurrentThread.Abort();
          }
          catch (ThreadAbortException)
          {
              Console.WriteLine("First");
              //Try to swallow it.
          } //CLR automatically reraises the exception here .
      }
      catch (ThreadAbortException)
      {
          Console.WriteLine("Second");
          Thread.ResetAbort();
          //Try to swallow it again .
      } //The in - flight abort was reset , so it is not reraised again .
      
      
      
      Output:
      First
      Second
      
    • Modify previous example to use different approach of ThreadAbortException instance creation:
      
      try
      {
          try
          {
              // get non-public constructor
              var cstor = typeof(ThreadAbortException)
                  .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
              // create ThreadAbortException instance
              ThreadAbortException ex = cstor.Invoke(null) as ThreadAbortException;
      
              // throw..
              throw ex;
          }
          catch (ThreadAbortException)
          {
              Console.WriteLine("First");
          } 
      }
      catch (ThreadAbortException)
      {
          Console.WriteLine("Second");
          Thread.ResetAbort();
      } 
      
      Output:
      First
      

    It seems like Thread's methods call native code internally which makes raised exception specific.

提交回复
热议问题