问题
I'm having an awful time with C# not freeing up memory for a large structure I'm holding in memory after I'm no longer referencing it.
I've included some code below that showcases a similar problem to the one I'm having. I think I must be misunderstanding something about the GC because I'm not sure why the following code would throw an Out of Memory Exception.
Does anyone know why the code I've included would throw out of memory? None of the lists are being held and they are immediately available to be cleaned up.
Thanks,
Paul
Repro: brand new 4.5 console application, paste the code into Main.
Exception will be thrown on the third "new List", in the first iteration of the for loop. If the for loop is omitted, the OOM will not occur.
for (var i = 0; i < 100; i++)
{
new List<int>(100 * 1000 * 1000);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
new List<int>(100 * 1000 * 1000);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
new List<int>(100 * 1000 * 1000);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
new List<int>(100 * 1000 * 1000);
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
}
回答1:
OK, this does reproduce but only under the following conditions:
- Fx 4.5, Platform = Any CPU, configuration = Debug .
By selecting either x64 platform or Release mode the program runs as expected.
So, tentative conclusion: with no-optimization the List<>
s remain rooted where they shouldn't be. And so the GC calls have no effect at all and the x86 memory space is quickly exhausted.
This may be a bug or it might a 'feature' aimed at debugging.
But while there does seem to be a problem it is very easily avoided.
来源:https://stackoverflow.com/questions/17578882/c-sharp-gc-not-freeing-memory