为什么这个简单的.NET控制台应用程序有这么多线程?控制台、线程、应用程序、简单

2023-09-02 21:08:16 作者:抛开世俗 ,

这个简单的程序始于15线程 - 根据计数。有时,它的生命周期中它丢弃了一些,但他们回来。

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);
         }
     }
 }

我期待的过程中只是有一个线程(和我的直觉是备份用的这个)

如果没有调试,这个过程只(!)4个线程。当然,任何CLR的东西会从我的过程中隐藏的?

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?

推荐答案

试着调试器(即preSS Ctrl + F5键代替F5)外运行它。您应该只看到三个线程 - 主线程,该线程的GC和放大器;终结器线程IIRC。你看到的其他线程调试相关的主题。

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.