2

My program seems to generate a lot of garbage then it calls an unmanaged dll function which allocates a lot of memory (~500+MB). The unmanaged function usually fails with an out of memory error. However if I call GC.Collect just before calling the unmanaged function, it never fails.

Task Manager shows the memory use climb monotonically then drop dramatically at the GC.Collect call. Without that call, it continues climbing till it fails.

Everything I read says "don't use GC.Collect except special cases". Could this be such a case? The only problem with calling GC.Collect seems to be that it might be slow. I don't care if it's slow so does that mean it's harmless?

4

1 回答 1

2

这听起来确实像是您可以调用的有效情况GC.Collect。您还可以尝试使用GC.AddMemoryPressure旨在告诉 CLR 您在进程中分配大量非托管内存的 API,这可能会影响 GC 更早执行收集的决定。

于 2013-08-20T19:55:59.237 回答