In this lesson, you will learn how to configure the .NET runtime host to transition from Workstation GC to Server GC to balance throughput against latency.
Workstation vs. Server Garbage Collection
By default, most .NET applications run on the Workstation GC, which is optimized for responsiveness in client-side apps. It typically runs on a single thread and minimizes the time the application pauses for collection. However, for high-scale services, this can become a bottleneck.
Server GC changes the strategy entirely. It creates a separate GC heap and a dedicated GC thread for every logical processor on your machine. By performing collections in parallel across these threads, Server GC significantly increases throughput—your application can process more requests per second. However, because it manages larger heaps and performs more complex parallel work, it can lead to longer individual "stop-the-world" pauses.
Configuring Runtime Settings
You don't need to change your C# code to enable Server GC; it is a configuration setting in your runtimeconfig.json file or your project file. To enable Server GC, set ServerGarbageCollection to true:
<PropertyGroup>
<ServerGarbageCollection>true</ServerGarbageCollection>
</PropertyGroup>
When to Use Each
- Workstation GC: Ideal for desktop applications or single-threaded background tasks where you want to keep pause times as short as possible.
- Server GC: Essential for ASP.NET Core web APIs, microservices, and high-concurrency environments.
If you find that your service is struggling with high throughput and the GC is becoming a bottleneck, switching to Server GC allows the runtime to distribute the pressure across your available CPU cores. If you notice that your latency spikes are too long for your specific requirements, you might also consider enabling Background GC (which is usually on by default with Server GC) to move much of the garbage collection work off the main threads, allowing your application to continue processing work during the collection process.
Key Takeaway: Use Server GC to maximize throughput in high-concurrency environments by distributing garbage collection across all available processor cores.