When is memory, allocated by .NET process, released back to Windows

My answer is – it doesn’t matter. The OS gives the application (within which the .NET runtime runs) virtual memory. This is not ‘real’ memory. The OS can put each page of virtual memory wherever it likes – on the processor, in main memory, on the disk. So, it is possible for an app to use more memory than the amount of RAM on the system, and the OS will copy the bits that are needed to/from disk to ensures the app keeps running (modulo certain addressing & technical limitations).

The OS manages the virtual memory of all the processes on the system, and ensures that one program doesn’t hog all the RAM on the system to the detriment of other programs. When the .NET runtime asks for memory from the system for use in the heaps, but then doesn’t use it, this memory will (if the system is low on free RAM) be moved to disk, because it isn’t being accessed.

Clarification via email from Tess: (emphasis mine)

The segment sizes stay the same throughout the course of the application, but there are two things to consider here.

  1. The allocations for a segment is a virtual allocation, meaning that while we reserve virtual memory, we only commit what we actually use, so the private bytes used for a segment is not the same as the segment size, this means that after a GC, your private bytes will go down, while your virtual bytes will stay the same.

  2. When a segment is no longer used, i.e. if you happen to GC everything in a segment so that it no longer contains any .net objects, the virtual alloc is returned back to the OS.

Taking that on faith, then heap segments (restaurant tables) will be returned back to the OS.

Leave a Comment