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.