I am trying to write a unit test using .NET 4 to ensure that an object can be garbage collected after some code is run. In Java, I would use assertGC to ensure that a weak reference is collected. How can I write this type of test for .NET?
I have tried keeping a WeakReference to the object and calling GC.Collect(), but as you’d expect, sometimes my object is collected and sometimes it is not. Note that this is for a unit test, not production code. I would not want GC.Collect() in my real code base.
I’m using C# but the same answer will be good for VB.NET too.
It looks like this isn’t possible at the moment with .NET 4. Though it is possible to know whether an object cannot be garbage collected (e.g. have a reference to it), there is no way to deterministically know whether an object can be garbage collected.
Using a WeakReference or a finaliser (and calling GC.Collect()) may collect the object, but unless it is in generation 0, there is a fair chance that it will not.
References: