Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple .NET console app have so many threads?

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?

like image 442
Matt Jacobsen Avatar asked Aug 13 '10 12:08

Matt Jacobsen


People also ask

What is .NET threading?

Threads are tasks that can run concurrently to other threads and can share data. When your program starts, it creates a thread for the entry point of your program, usually a Main function. So, you can think of a "program" as being made up of threads.

Can you run out of threads C#?

If your ThreadPool runs out of threads two things may happen: All opperations are queued until the next resource is available. If there are finished threads those might still be "in use" so the GC will trigger and free up some of them, providing you with new resources.

How many threads can we create in C#?

32767 in Framework 4.0 (64-bit environment)


2 Answers

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.

like image 71
Phil Devaney Avatar answered Sep 20 '22 06:09

Phil Devaney


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

like image 33
Hans Passant Avatar answered Sep 19 '22 06:09

Hans Passant