views:

809

answers:

4

I created a console app in c# with a single console.readline statement. Running this app within visual studio and stepping into the debugger shows 7 thread in the thread window (6 worker threads, one is .NET SystemEvents and the other is vshost.RunParkingWindow and the main thread). When I run the app outside visual studio I see a total of 3 threads in windows task manager. Why so many? I would expect 1 thread? What are the others being spawned for?

Thanks

A: 

They must be sleeping. Unfortunately sometimes Microsoft does not always practice what it preaches. If you don't trust me, check the number of threads used by your visual studio or the Microsoft outlook by enabling the threads column in your process explorer window of Windows Task manager.

CodeToGlory
What does this have to do with the question?
Samuel
I am just adding some information that I see can help him as there are lot of namespaces that can do initiate threads but may very well be sleeping as they may not be using ThreadPool.Besides, atleast it is not like I ask a question myself and answer it as well.http://stackoverflow.com/questions/296632/apache-access-control
CodeToGlory
From the FAQ: It's also perfectly fine to ask and answer your own programming question, but pretend you're on Jeopardy: phrase it in the form of a question.
Andy Mikula
+21  A: 

If you're running a .NET application, I believe you always get a thread (mostly sleeping) for the JIT as well as the GC thread, in addition to your main thread.

Reed Copsey
+1  A: 

Don't forget that finalizer thread !

Brann
There is no such thing as a finalizer thread; however, there is a GC thread.
Samuel
@Samuel : the full name is in fact the GC Finalizer Thread, or at least that's what google seems to say. the Accepted Answer has been edited during the 5mn initial timeframe to add GC, which it doesn't in its original version, thus my answer.
Brann
Uh, yes there is a finalizer thread. It runs at low priority in the background to process a queue that the GC sets up. The GC itself does not necessarily run in a separate thread from your application.
Promit
+2  A: 

There is a way to move SystemEvents notifier into your thread:

public static class ThreadingHelper_NativeMethods
{
   [DllImport("user32.dll")]
   public static extern bool IsGUIThread(bool bConvert);
}


     // This code forces initialization of .NET BroadcastEventWindow to the UI thread.
     // http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/fb267827-1765-4bd9-ae2f-0abbd5a2ae22
     if (ThreadingHelper_NativeMethods.IsGUIThread(false))
     {
        Microsoft.Win32.SystemEvents.InvokeOnEventsThread(new MethodInvoker(delegate()
        {
           int x = 0;
        }));
     }
GregC