The answer to sorting is that this is probably not the best solution - instead of anticipating when you are going to run out of memory and try to do something, you probably should either try to reduce the memory consumption of your application, or just to until an OutOfMemoryException is thrown and then flushed .
An exception is excluded whenever the .Net runtime cannot allocate the requested memory - this may be because the computer has run out of physical memory and the page file has been disabled (or the machine has run out of disk space), or it may be due to the fact that the virtual memory space of the process is too fragmented to allocate the required block of memory (which can happen when working with large objects). Predicting when it will be quite difficult.
You can use the MemoryFailPoint class to check whether access to a specific amount of memory will be available before starting an operation that uses a large amount of memory, however this class does not guarantee that the memory will remain available for the entire duration of the operation, and therefore your application may still exit out of order with the exception of OOM. Although this class may be useful in some scenarios to try to reduce OOM exceptions (and, in turn, so as not to damage the state of the application), it will probably not be the magic bullet solution for your problem.
Justin
source share