I have a method that needs to process a user-supplied file and if the file is complex enough I may encounter an OutOfMemoryException
. In these cases I'm fine with the method failing however I would like the application to remain usable, the problem is that after getting an OutOfMemoryException
I can't do anything since every course of action consumes memory.
I thought of putting aside some memory which I can free once the exception is throw so the rest of the application can carry on but it seems that the optimizer gets rid of this allocation.
public void DoStuff(string param)
{
try
{
#pragma warning disable 219
var waste = new byte[1024 * 1024 * 100]; // set aside 100 MB
#pragma warning restore 219
DoStuffImpl(param);
}
catch (OutOfMemoryException)
{
GC.Collect(); // Now `waste` is collectable, prompt the GC to collect it
throw; // re-throw OOM for treatment further up
}
}
Long story short my questions are:
- Is there a better way to do what I'm attempting?
- If not, is there a good reason why this is a bad idea?
- Assuming this idea is the way to go, how do I force the JIT to not optimize away my
waste
d memory?