2

Is there any way to check what instances classes are collected by GC and what are not? The one option i found is by checking class by Test as described here:

How can I write a unit test to determine whether an object can be garbage collected?

Community
  • 1
  • 1
Spirosi
  • 324
  • 1
  • 15
  • 5
    Where do you need this? – thijmen321 May 15 '15 at 14:36
  • Classes aren't collected by GC, but instances of all classes are. In general you can test collection by having a weak reference to it and seeing if its still alive, but just how best to do that might depend on just what you need. – Jon Hanna May 15 '15 at 14:46
  • @JonHanna, sorry, missed "instances" word. I'm trying to write code in a proper way and avoid memory leaks. So i want to check what instances are still "Alive" even if i'm not using them and they shuold be collected. – Spirosi May 18 '15 at 05:04

3 Answers3

2

Is there any way to check what classes are collected by GC and what are not?

No, because to check on an object you'd still need a reference to it and that would prevent its collection.

You can build an administration with WeakReferences but that would be awkward and costly. Certainly not feasible for all objects.

More important, you shouldn't be needing this. If you think you do, analyze that thought train.

H H
  • 263,252
  • 30
  • 330
  • 514
0

create a ReferenceTester class that will hold A Dictionary of week references Dictionary use them to test if class is there. then call GC.Collect().

then check ReferenceTester again if class is still there.

Nahum
  • 6,959
  • 12
  • 48
  • 69
-1

You can also tell when an object has been Garbage Collected with the finalizer is called. This is not 100% guaranteed as you still call GC.SupressFinalize() on classes that will prevent the collection.

mageos
  • 1,216
  • 7
  • 15
  • There is a whole a raft of reasons why a finalizer might not be called, and `SuppressFinalize()` is the least of them. There is no guarentee that a finalizer will ever be called. – Binary Worrier May 15 '15 at 14:51
  • And having a Finalizer (destructor) is very expensive. You don't want that on all (many) of your objects. – H H May 15 '15 at 14:56