With more and more workloads running in the cloud, optimizing the resource consumption becomes an important feature of every application. Being able to dynamically scale down the memory limit can help us reduce costs when demand decreases.
However before .NET 8, when a service tried to decrease the memory limit on the fly, it could fail as the .NET garbage collector was unaware of this change and would still allocate more memory.
No longer in .NET 8! A new API was introduced that allows to adjust the memory limit on the fly:
This will instruct the garbage collector to reconfigure itself by detecting the various memory limits on the system. Calling this API can result in an InvalidOperationException
when the newly set limit is lower than what's already committed.
Remark: For smaller workloads it can also be useful to switch from Server GC to Workstation GC, which optimizes for lower memory usage. The switch can be done by adding this flag to your csproj file: