views:

304

answers:

4

This simple program starts with 15 threads - according to the count. Sometimes during its lifetime it drops a few, but they come back.

class Program
 {
     static void Main(string[] args)
     {
         while (true)
         {
             Console.WriteLine(Process.GetCurrentProcess().Threads.Count);
             Thread.Sleep(500);
         }
     }
 }

I was expecting the process to just have one thread (and my intuition was backed up by this)

Without the debugger, the process has only (!) 4 threads. Surely any CLR stuff would be hidden from my process?

What count is this? Does the process really have that many threads? Why?

+6  A: 

If you run it without a debugger attached, there are significantly fewer threads. And those would presumably be the finalizer thread, and other house-keeping CLR stuff.

HTH,
Kent

Kent Boogaart
+4  A: 

Try running it without the debugger (Visual Studio) attached (Ctrl+F5). You'll see that there will be less (probably 3) threads. Most of those threads have to do with the debugger.

BFree
+19  A: 

Try running it outside the debugger (i.e. press Ctrl+F5 instead of F5). You should only see three threads - the main thread, the GC thread & the finalizer thread IIRC. The other threads you see are debugger-related threads.

Phil Devaney
Yes, main thread, GC, and finalizer are exactly what you will see. However you need to A) run outside the debugger and B) turn off Visual Studio Hosting Process which adds a thread or two.
Tergiver
do you have a link to an msdn article?
Matt Jacobsen
is the VS hosting process activated even if I'm in Release mode without running the process through VS? I still see 4 threads...
Matt Jacobsen
Thread 4 might be a ThreadPool thread for any asynchronous work that needs to be done. Just guessing, though.
Sander
+1  A: 

Project + Properties, Debugging, untick "Enable the Visual Studio hosting process". I can't discover what it is doing. As soon as I tick the "Enabled unmanaged code debugging" option to try to get a peek at these threads, they no longer get started. No clue. But I'm sure it's for our benefit :)

Hans Passant
I think the hosting process gives the debugger go faster stripes, or something like that.
Matt Jacobsen
I beleive the hosting process was designed to give faster startup times for debugging - when you debug, the relevant assemblies get loaded into the vshost process, rather than the debugger having to keep on creating/destroying new processes.
Alex Humphrey
Nah, the hosting process is a custom hosted version of the CLR. Mostly for security purposes.
Hans Passant