Hooking thread exit

Posted by mackenir on Stack Overflow See other posts from Stack Overflow or by mackenir
Published on 2009-07-26T13:43:28Z Indexed on 2010/12/24 6:54 UTC
Read the original article Hit count: 444

Filed under:
|
|
|
|

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?)

I've developed a mechanism for hooking thread exit that works for some 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).

This mechanism works on, for example, worker threads that I create in code using the Thread class.

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.

(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.))

© Stack Overflow or respective owner

Related posts about com

Related posts about clr