.NET垃圾收集器线程数线程、垃圾、收集器、NET

2023-09-06 19:28:38 作者:作为听众

多少这些运行在任何给定的时间?它是一个用于整个框架,或每.NET托管过程中的一个?当物理内存是丰富,是正确的假设不存在活动的GC线程?

How many of these run at any given time? Is it one for the entire Framework, or one per .NET managed process? When physical memory is in abundance, is it correct to assume there are no active GC threads?

推荐答案

有.NET垃圾收集,服务器和工作站两种模式。对于工作站,你将有每个.NET过程中的一个垃圾收集器线程。如果你正在运行的服务器的垃圾收集模式,你将有每个进程和处理器都有一个垃圾收集器线程。所以,如果你有一个4核CPU上运行的服务器中的.NET过程中,你将有4个垃圾收集器线程。

There are two modes of .NET garbage collection, server and workstation. For workstation, you will have one garbage collector thread per .NET process. If you are running server garbage collection mode, you will have one garbage collector thread per process and processor. So if you have a .NET process running as server on a 4 core CPU, you will have 4 garbage collector threads.

此外,对.NET 4,一个新的后台垃圾收集模式存在。它会收集在第0代和1个并行项目。

Also, for .NET 4, a new "background garbage collection" mode exists. It will collect items in generation 0 and 1 concurrently.

如果你有足够的物理内存垃圾收集甚至可能发生。 .NET将分配内存的块堆。一般而言,这样的事情发生了:当需要内存,.NET将试图找到内存上的堆块,将适合需要的内存块。如果不成功,一个GC运行,试图收集任何不需要的对象。只有当这不能释放足够的内存,新的内存块将被分配给从底层操作系统堆。

Garbage collection might happen even if you have plenty physical memory. .NET will allocate memory for its heap in blocks. In general terms, something like this happens: When new memory is needed, .NET will try to find a block of memory on it's heap that will fit the required memory chunk. If unsuccessful, a GC will run to try to collect any unneeded objects. Only if that does not free enough memory, a new block of memory will be allocated for the heap from the underlying OS.

细节与MSDN文章中,的垃圾收集基础。

Details are in the MSDN article, Fundamentals of Garbage Collection.

这一切都被说,我非常赞同one其他的答案的关于这个问题: 不要在GC上任何假设。它应该是无关的应用程序内存是如何分配和回收。

All this being said, I highly agree with one of the other answers on this question: Do not make any assumptions on the GC. It should be irrelevant to your application how memory is allocated and collected.