A reasonable workaround to calling GC.collect
would be to create a new MemoryFailPoint before the critical code section.
This of course does not solve the the real problem, why the GC in your case did not collect the memory by itself.
In your case you know how much memory you will need (the file size), so by creating a new MemoryFailPoint with that size, you can be reasonably certain the memory will be available. MemoryFailPoint actually calls GC.Collect
itself, if it decides it is neccessary, but it also has some additional logic deal with other issues such as page file size or address space fragmentation.
And if the memory is not enough, you avoid an OutOfMemoryException
with its potential corrupting side effects, and instead get an InsufficientMemoryException
, which can be caught without worries.