4

I am using this code snippet below to list the threads in a basic console app.

lock (threadLock)
{
    ProcessThreadCollection currentThreads = Process.GetCurrentProcess().Threads;
    foreach (ProcessThread thread in currentThreads)
    {
        Console.WriteLine(" Id={0}, CurrentPriority={1}, State={2}",
                          thread.Id, thread.CurrentPriority, thread.ThreadState);
    }
}

There are six threads. Below, is the initial output.

Id=2924, CurrentPriority=8, State=Running
Id=8900, CurrentPriority=8, State=Wait
Id=524, CurrentPriority=8, State=Wait
Id=4916, CurrentPriority=8, State=Wait
Id=5124, CurrentPriority=8, State=Wait
Id=6780, CurrentPriority=11, State=Wait

Apparently, the first thread is the main thread. The last one, with CurrentPriority=11, is the Finalizer thread because below is the output when run inside a destructor:

Id=2924, CurrentPriority=8, State=Wait
Id=8900, CurrentPriority=8, State=Wait
Id=524, CurrentPriority=8, State=Wait
Id=4916, CurrentPriority=8, State=Wait
Id=5124, CurrentPriority=8, State=Wait
Id=6780, CurrentPriority=11, State=Running

My question is about the other four threads. One of them is supposed to be UI thread. Another is supposed to be a Garbage Collector (GC) thread. Apparently, one is supposed to be a Threadpool thread. What is the last sixth thread? What are the code snippets for each one so that I can run each individual thread? Does GC thread ever execute application code? A lot of sources mix up Finalizer and GC threads so it is hard to figure out whether these are seperate threads or one thread. It would be helpful to have code snippets for each one so that I can actually run each thread.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lola Wecv
  • 109
  • 5
  • The linked Q+A is outdated. To get 6 threads, you'd typically have to run the program without a debugger and run it on Win10. Win10 typically adds 4 extra threads from the OS thread-pool, used by the loader to get DLLs initialized faster. If you use a debugger then you get 2 more threads. The debug thread itself, used to evaluate watch expressions, and a "canary thread" whose sole job it is to check if locks in code run by the debug thread are safe. So, as-is it is main thread, finalizer thread plus 4 OS tp threads. – Hans Passant Oct 07 '17 at 14:30
  • For my case, Debug and Release have the same count of 6 threads. Where is the duplicate question? Does it mean that GC thread is one of the four threads added by OS (Windows 10 in my case)? – Lola Wecv Oct 07 '17 at 15:15
  • There is no GC thread on a workstation machine, just the finalizer thread. And no, those 4 added threads are pure unmanaged threads. The OS likes to use threads too to get stuff done quicker. – Hans Passant Oct 07 '17 at 15:22
  • Debut and Release have nothing to do with the debugger being attached or not, it very well can in a Release version. – InBetween Oct 07 '17 at 18:12

0 Answers0