.NET Basic – Background Garbage collection

Spread the love

Background garbage collection is replaces the concurrent garbage collection in .NET 4.0. It is applicable on desktop garbage collection. But later, it was added for Server Garbage collection too in .NET 4.5.

  • Background garbage collection collect the generation 0 and 1 object while the collection generation 2 is in progress.
  • It uses one or more dedicated threads depending upon Workstation or Server Garbage Collection.
  • It is applicable only duration of generation 2 garbage collection dependent on requirements.

Most confusing part here is when background garbage collection is in progress and application allocated enough object in generation then generation 0 and 1 garbage collection starts in foreground. During that time background thread suspends itself. Once Foreground garbage collection finishes it’ll restart the background process.

Background GC – Workstation vs Server

It function similar in both workstation and server with following differences:

  • Workstation background GC uses one dedicated thread while Server process uses multiple threads. Typically one thread for each logical processor.
  • Unlike workstation background GC, Server background GC does time out

Workstation vs server GC

Workstation GC is a default GC flavor for standalone apps. It can be concurrent or non-concurrent. Concurrent also called background garbage collection allow managed threads to continue operations during garbage collection.

Server GC can also be non-concurrent for background. Server GC has dedicated threads that perform the garbage collection. There will be one or more thread per logical processor.

Performance Considerations

  • The collection occurs on the user thread that triggered the garbage collection and remains at the same priority. Mostly user threads runs at normal priority hence the GC thread is also on norma priority and compete with other threads for CPU timing.
  • Workstation GC is always used on computer that has only one logical CPU, regardless of the configuration.
  • Server GC
    • The collection occurs on multiple dedicated threads that are running at highest priority level.
    • Because multiple garbage collection threads work together, server gc is faster that workstation GC on same size heap.
    • Server garbage collection can be resource-intensive. If there are many process running using GC. All those try to schedule on those cpu and too much context switching may cause performance issue.

If there are running hundreds of instances of an application consider using workstation garbage collection with concurrent/background garbage collection disabled. This will result in less context switching, which can improve performance.