How I can know to tell if an Object has been garbage collected or not?
Asked
Active
Viewed 1.0k times
17
-
The 'duplicate' question is not very specific, so reopened. This asks a specific question and has a specific answer. – leppie Jul 27 '16 at 18:07
1 Answers
47
According to this:
You normally can’t tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won’t be garbage collected.
You can instead create a weak reference to an object using the WeakReference object. The weak reference is one that won’t be counted as a reference, for purposes of garbage collection.
In the code below, we check before and after garbage collection to show that a Dog object is garbage collected.
Dog dog = new Dog("Bowser");
WeakReference dogRef = new WeakReference(dog);
Console.WriteLine(dogRef.IsAlive);
dog = null;
GC.Collect();
Console.WriteLine(dogRef.IsAlive);

The_Black_Smurf
- 5,178
- 14
- 52
- 78

user2110292
- 3,637
- 7
- 22
- 22
-
This trick is useful in the case of unit testing some hand-made container with a „Clear“ method. – Denis Gladkiy Jul 01 '19 at 05:14
-
3This trick can fail in the case of debug mode: all local objects are „hooked“ until the end of the method. So, If you are writing some kind of unit test, the above code should be wrapped into a method and the weak reference (as well as GC.Collect() call) must be checked after the wrapper invocation. – Denis Gladkiy Jul 01 '19 at 05:38