Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you stick to standard coding in .NET, is there reason to manually invoke the GC or run finalizers?

If you stick to managed code and standard coding (nothing that does unconventional things withe CLR) in .NET, is there any reason to manually invoke the GC or request to run finalizers on unreferenced objects?

The reason I ask is thaty I have an app that grows huge in Working Memory set. I'm wondering if calling

System.GC.Collect();

and

System.GC.RunFinalizers();

would help, and if it would force anything that wouldn't be done by the CLR normally anyways.

like image 435
Matt Avatar asked Dec 10 '22 15:12

Matt


2 Answers

No, it won't help. Don't do it. The CLR already handles all the memory management-related stuff in a fine way, and no explicit call will do something it's not already doing.

Try to look for memory leaks in your program: while .NET languages are memory-managed, it doesn't mean it always knows when you're not using a certain object anymore. For instance, objects attached as event listeners to other objects are considered rooted by the GC and won't be collected.

You can try SOS to seek leaks.

If there is really no leak, then your program truly needs the memory it has.

like image 167
zneak Avatar answered Jun 01 '23 05:06

zneak


@zneak : Actually, this isn't entirely true. I ran into a situation in which I was intermittently and non-deterministically running out of memory while running through a large set of data (that involved a lot of creating and destroying managed objects) in c#.

Manually invoking garbage collection once per loop fixed it. However, this is rare, and in most cases leaving the garbage collector to itself is the best course, however, I wouldn't make a blanket statement that one should never manually invoke GC as that is simply incorrect.

like image 20
Donnie Avatar answered Jun 01 '23 05:06

Donnie