I am embarking in a series of mini post called .NET hidden gems, not necessarily new bits but usually unknown. They are dedicated to those small features and components that are not commonly used but can deliver interesting value in certain scenarios.
Today I am going to show you some functions that can help you to understand the memory state of your application when you need to store large objects.The first hidden gem is the MemoryFailPoint object, this can be accessed through the System.Runtime namespace. The main function of it is validating that there is enough memory to perform an operation.
[SecurityCritical]public MemoryFailPoint(int sizeInMegabytes);
It is very easy to use it, just create an instance when you need the memory:
//// Do I have enough memory to run this method?//System.Runtime.MemoryFailPoint CheckForMemory = new System.Runtime.MemoryFailPoint(1000);Internally, it checks the global memory status of the process; if it does not have enough it will perform a full collection. If it has enough it will execute a virtual allocation for that amount of bytes. This is really important as the MemoryFailPoint will reserve the memory for your application and it won’t be available for other resources until is freed using the Dispose() function, so use it with care.
If you want to know more about Memory managent in .NET please check my other post here