Is the garbage collector running in a separate pro

2020-05-24 20:56发布

问题:

Does the garbage collector start in a separate process?

For example:

  1. If we try to measure process time taken by some piece of code and during this the garbage collector starts collecting, will it start on a new process or in the same process?

  2. Is it working like the following?

    //Code (Process 1)
    --> Garbage Collector Run (Process 1)
    //Code (Process 1)
    

    Or like this?

    //Code (Process 1)
    --> Garbage Collector Run (Process 2)
    //Code (Process 1)
    

回答1:

The garbage collector runs the thread that triggered garbage collection, on the very same process. It stops all current thread, and executes itself. It doesn't start another process for sure, you would have seen that in Windows.

From MSDN:

Before a garbage collection starts, all managed threads are suspended except for the thread that triggered the garbage collection.

(This applies to workstations only, as pointed out by DrKoch). Servers have a background thread running for garbage collection.

If you search in the referenced documentation for "Concurrent garbage collection", you will the text "GC thread", which supporting this.

You can force to run garabage collection in a separate thread, if you want to. Put this in your app.config:

<configuration>
   <runtime>
      <gcServer enabled="true"/>
   </runtime>
</configuration>

(from this answer)

Also read The .NET Framework 4.5 includes new garbage collector enhancements for client and server apps, as suggested by Adam Houldsworth, about changes in the way the garbage collector works since .NET 4.5.



回答2:

First there is a distinction between process and thread. As pointed aout by @CodesInChaos each process has its own adress space, so running GC in a separate process makes no sense.

If we talk about threads: there is a difference between "Workstation" and "Server". On a workstation it runs on one of the user threads:

The collection occurs on the user thread that triggered the garbage collection

On a server it runs in separate, dedicated threads:

The collection occurs on multiple dedicated threads that are running at THREAD_PRIORITY_HIGHEST priority level.

If your machine is considered a "server" depends on configuration:

<gcServer> element of the runtime configuration schema

See Fundamentals of Garbage Collection