Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Visual Studio's Thread Window Identify the "Main Thread'

I am likely missing something obvious, but humor me...

I always like to name the important threads in my apps as it is useful with debugging/logging etc. If you query the main thread's name via Thread.CurrentThread.Name at program startup you will get back null. As such, I always ensure that the first thing that happens is that the main thread (and any other relevent threads) get assigned a nice meaningful name for future reference.

I never really gave it much thought until today, but when looking at the Threads window in Visual Studio (before any thread names are assigned etc), a special category 'Main Thread' is assigned as well as a psuedo name that also reads "Main Thread" (but that isn't the actual thread name).

From a managed perspective, .NET doesn't expose anything meaningful on either System.Threading.Thread or System.Diagnostics.ProcessThread that identifies an application's main thread (at least that I could see). I looked at the list of Windows Process and Thread Functions, and again, I didn't see anything obvious (perhaps OpenThread?).

Curious if anyone knows how the Threads window assigns the special category "Main Thread"?

like image 653
Chris Baxter Avatar asked Feb 03 '11 20:02

Chris Baxter


1 Answers

The debugger starts debugging with CreateProcess using the DEBUG_PROCESS option. The main thread's handle is returned in PROCESS_INFORMATION.hThread so no guessing there. Attaching is a bit trickier, presumably the first CREATE_THREAD_DEBUG_EVENT notification its sees from WaitForDebugEvent after attaching with DebugActiveProcess().

The source code for MDbg is available if you want to take a closer look.

like image 175
Hans Passant Avatar answered Sep 29 '22 00:09

Hans Passant