[SOLVED] Detect New Thread Spawned in .NET


I’m trying to implement some performance instrumentation for our Windows Forms app and I’d like to detect when a new thread is spawned (specifically from the UI thread) and watch for when it exits. I know I can catch the thread exit event on


But I need to find out when a new thread is invoked using the ThreadPool (or BackgroundWorker, which uses the ThreadPool under the hood). Ideally I’d also like to get the StackFrame where it’s invoked from.

Anyone know of a way of doing this? WMI perhaps?



Add a native DLL to your application that triggers required processing on DLL_THREAD_ATTACH in DllMain.

This is the only way to reliably detect all thread creation in a process.

EDIT: This is going to be problematic, because managed threads and native threads do not correspond 1-1. I think you might have to leverage the managed thread debugging support to do what you want. Painful but it should work. For example see ICorDebugThread.

Represents a thread in a process. The
lifetime of an ICorDebugThread
instance is the same as the lifetime
of the thread it represents.

and ICorDebugProcess has some useful tools for you.

You don’t really want to write a debugger, but you do want this level of inspection for for your managed threads. The motherlode might be ICorDebugManagedCallback::CreateThread.

Notifies the debugger that a thread
has started executing managed code.

There is a corresponding ExitThread callback.

Answered By – Steve Townsend

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *