title: Hooking thread exit
body: <p>Is there a way for me to hook the exit of managed threads (i.e. run some code on a thread, just before it exits?)</p>
  
  <p>I've developed a mechanism for hooking thread exit that works for <em>some</em> threads. Step 1: develop a 'hook' STA COM class that takes a callback function and calls it in its destructor. Step 2: create a ThreadStatic instance of this object on the thread I want to hook, and pass the object a managed delegate converted to an unmanaged function pointer. The delegate then gets called on thread exit (since the CLR calls IUnknown::Release on all STA COM RCWs as part of thread exit).</p>
  
  <p>This mechanism works on, for example, worker threads that I create in code using the Thread class.</p>
  
  <p>However, it doesn't seem to work for the application's main thread (be it a console or windows app). The 'hook' COM object seems to be deleted too late in the shutdown process and the attempt to call the delegate fails.</p>
  
  <p>(The reason I want to implement this facility is so I can run some native COM code on the exiting thread that works with STA COM objects that were created on the thread, before it's 'too late' (i.e. before the thread has exited, and it's no longer possible to work with STA COM objects on that thread.))</p>