title: How does Thread.Abort() work?
body: <p>We usually throw exception when invalid input is passed to a method or when a object is about to enter invalid state. Let's consider the following example </p>
  
  <pre><code>private void SomeMethod(string value)
  {
      if(value == null)
          throw new ArgumentNullException("value");
      //Method logic goes here
  }
  </code></pre>
  
  <p>In the above example I inserted a throw statement which throws <code>ArgumentNullException</code>. My question is how does runtime manages to throw <code>ThreadAbortException</code>. Obviously it is not possible to use a <code>throw</code> statement in all the methods, even runtime manages to throw <code>ThreadAbortException</code> in our custom methods too. </p>
  
  <p>I was wondering how do they do it? 
  I was curious to know what is happening behind the scenes, I opened a reflector to open <code>Thread.Abort</code> and end up with this</p>
  
  <pre><code>[MethodImplAttribute(MethodImplOptions.InternalCall)]
  private extern void AbortInternal();//Implemented in CLR
  </code></pre>
  
  <p>Then I googled and found this <a href="http://www.sellsbrothers.com/writing/askthewonk/HowdoestheThreadAbortExce.htm" rel="noreferrer">How does ThreadAbortException really work</a>. This link says that runtime posts APC through <code>QueueUserAPC</code> function and that's how they do the trick.
  I wasn't aware of <code>QueueUserAPC</code> method I just gave a try to see whether it is possible with some code. Following code shows my try.</p>
  
  <pre><code>[DllImport("kernel32.dll")]
  static extern uint QueueUserAPC(ApcDelegate pfnAPC, IntPtr hThread, UIntPtr dwData);
  delegate void ApcDelegate(UIntPtr dwParam);
  
  Thread t = new Thread(Threadproc);
  t.Start();
  //wait for thread to start
  uint result = QueueUserAPC(APC, new IntPtr(nativeId), (UIntPtr)0);//returns zero(fails)
  int error = Marshal.GetLastWin32Error();// error also zero
  
  private static void APC(UIntPtr data)
  {
      Console.WriteLine("Callback invoked");
  }
  private static void Threadproc()
  {
      //some infinite loop with a sleep
  }
  </code></pre>
  
  <p>If am doing something wrong forgive me, I have no idea how to do it. Again back to question, Can somebody with knowledge about this or part of CLR team explain how it works internally? 
  If <code>APC</code> is the trick runtime follows what am doing wrong here?</p>