user1318499
user1318499

Reputation: 1354

Call GC.Collect before memory hungry unmanaged function?

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?

Upvotes: 2

Views: 229

Answers (1)

Sasha Goldshtein
Sasha Goldshtein

Reputation: 3519

It does sound like a valid situation in which you would call GC.Collect. You could also try the GC.AddMemoryPressure API which is designed to tell the CLR that you are allocating a lot of unmanaged memory in your process, and might influence the GC's decision to perform a collection earlier.

Upvotes: 2

Related Questions