ThreadAbortExceptionその2

http://d.hatena.ne.jp/akiramei/20050113#p4の続き。

Zoltan Varga氏よりコメントを頂く。

This happens because signal_thread_state_change does not call mono_thread_request_interruption directly, but queues an APC call to do it.

これによると、Thread.CurrentThread.Abort()を呼び出しても、すぐに例外が発生する訳ではなく、一度キューに入れられて、APC(Asynchronous Process Controlの略で良いのかな?)によって発生させられるってことらしいです。以下、確認のためのコード。

using System;
using System.Threading;

public class X
{
  public static void Main ()
  {
    try {
      Thread.CurrentThread.Abort ();
      // thread change 
      Thread.Sleep (0);
      Console.WriteLine ("1");
    }
    catch {
      Console.WriteLine ("2");
      try { 
        Console.WriteLine ("3");
      } catch { 
        Console.WriteLine ("4");
      } 
      Console.WriteLine ("5");
    }
    Console.WriteLine ("6");
  }
}

/* MS.NET
 2
 3
 5
 */

/* Mono 
 1
 6
 */

/* Mono Thread.Sleep (0)
 2
 3
 5
 */

Thread.Sleep(0)でスレッドの切り替えを起こすと確かにMS.NETと同じ動きになりますね。