What does the CLR do before throwing an OutOfMemor

2019-07-27 16:17发布

问题:

I would like to know precisely what the CLR does before it throws an OutOfMemoryException (OOME). I understand that the likely cause is not having a contiguous chunk of memory available, but does the CLR proactively do anything before making this determination? (e.g. collect, compact heap, etc.)

This answer and this one suggest that the GC does do something prior to throwing OOME and that doing something after can alleviate the OOME. That said, this response seems to contradict the latter answer.

The reason for this question is that under heavy load, we've seen the OOME and want to alleviate the conditions that cause this. One of the strategies we've tried is running this code when catching an OOME:

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

This would be redundant if the CLR has already done something like this just prior to choosing to throw the exception.