I need to refactor my project in order to make it immune to OutOfMemory exception.
There are huge collections used in my project and by changing one parameter I can make my program to be more accurate or use less of the memory…
OK, that’s the background. What I would like to do is to run the routines in a loop:
- Run the subroutines with the default parameter.
- Catch the
OutOfMemoryexception, change the parameter and try to run it again. - Do the 2nd point until parameters allow to run the subroutines without throwing the exception (usually, there will be only one change needed).
Now, I would like to test it. I know, that I can throw the OutOfMemory exception on my own, but I would like to simulate some real situation.
So the main question is:
Is there a way of setting some kind of memory limit for my program, after reaching which the OutOfMemory exception will be thrown automatically?
For example, I would like to set a limit, let’s say 400MB of memory for my whole program to simulate the situation when there is such an amount of memory available in the system.
Can it be done?
I’d like to suggest another way of looking at this. You don’t necessarily have to run out of memory. You just need to monitor the amount of memory used, and compare it to the total system memory. Perhaps something like GC.GetTotalMemory will be useful here to see how much memory your application is using. Then perhaps this article will help with getting the total amount of physical RAM available on your system.