Alex Rivera | Logout

Should I ever manually force garbage collection in my WPF app?

Asked 2011-04-22T15:50:49.100
13

I've just been sorting out some memory leaks in my WPF application. To do so, I used the CLR profiler, as well as watching process statistics in Windows Task Manager. My basic test was to make sure that when a certain window was closed, it didn't still hang around in memory.

I'm slightly new to windows development, and at first I was getting confused because in a simple test application, it seemed as if no matter what, my windows were always staying in memory after being closed. But I eventually worked out that this did not mean there was a memory leak, but just simply that they hadn't been garbage collected yet. So I had to create a button in my main window hooked up to an event handler that contained code to manually force garbage collection. By manually garbage collecting, I could then complete my memory leak tests, and I got it all sorted.

But it got me thinking - is there ever a need to manually force garbage collection?

It pains me to watch my application's memory consumption go up and up as I open and close windows. Of course, eventually, garbage collection automatically runs and it all gets sorted out. But it almost seems like a good idea to manually garbage collect after these heavy windows get closed. But is there any point? I get the feeling that testing aside, we are not supposed to force garbage collection - just let the system sort it out.

Thoughts appreciated.

Edit
Report

2 Answers

3

I agree with you on both sides of your point :-). I generally take the approach that the people who wrote the .NET runtime are smarter than I am and have a better understanding of garbage collection than I do, so I leave it alone.

I have seen a few instances where people thought they were doing good by forcing garbage collection, but there was never any hard evidence that it helped.

answered 2011-04-22T15:54:43.947
2

The only time I use GC.Collect is to quickly find out how much memory is ready to be collected.

Otherwise it is useless because up until now the GC is smarter than I am.

answered 2011-04-22T16:52:45.413

Your Answer