6

I'm trying to make sure instances of a certain class get released, by using console.WriteLine() in the destructor, but the output never shows up.

I have carefully searched for any lingering references, as well as event subscriptions and not finding any. Just for my own sanity, and before I continue my search, can someone confirm that:

GC.Collect();
GC.WaitForPendingFinalizers();

Will force a complete reclaim, no matter how small the objects are?

Jamona Mican
  • 1,574
  • 1
  • 23
  • 54

1 Answers1

6

In general, this should clean up most things.

However, if you have code in your finalizers, it's possible that you will need to call GC.Collect() twice, as the first time will cause the finalizers to execute, but the actual memory cannot be cleaned until after the finalizer has completed, which means the subsequent call will catch the object.

Community
  • 1
  • 1
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • oh well. my search continues then. I would KILL for a GC.GetListOfReferences(object) command... Seems like it would be quite useful! – Jamona Mican Sep 21 '12 at 17:26
  • 1
    @HarryMexican You can use SoS to get the list of references in the debugger, as well as many .NET memory profilers. See: http://stackoverflow.com/q/707421/65358 – Reed Copsey Sep 21 '12 at 17:37
  • Thanks Reed. I would not have figured it out without Memory Profiler. Noticed ConcurrentQueues were holding references despite being empty. Then found this: http://blogs.msdn.com/b/pfxteam/archive/2012/05/08/concurrentqueue-lt-t-gt-holding-on-to-a-few-dequeued-elements.aspx Sure enough, after running enough traffic through the system, the ConcurrentQueue starting releasing and the GC starting finalizing. Yay! – Jamona Mican Sep 21 '12 at 18:44
  • Take a look at http://blogs.msdn.com/b/dotnet/archive/2013/05/01/net-crash-dump-and-live-process-inspection.aspx it gives you functionality similar to SOS just without any extra processes, setup etc. – MichalMa Jun 05 '13 at 06:56