I'd like to verify that code setting up a
Does this look like the best way to check for inadvertent strong references?
TestObject testObj = new TestObject();
WeakReference wr = new WeakReference(testObj);
// Verify that the WeakReference actually points to the intended object instance.
// Force disposal of testObj;
testObj = null;
// If no strong references are left to the wr.Target, wr.IsAlive will return false.
I got in touch with Microsoft about this and learned/confirmed that:
GC.Collect()forces a blocking garbage collection.
GC.Collect()runs, it won't mysteriously skip over collection-eligible objects. Predictable rules are followed for determining which objects to collect. As long as you operate with an understanding of those rules (i.e. how finalizable objects are handled), you can force a particular object to be destroyed though the memory used by the destroyed object may or may not be freed.
More information on my blog: Can .Net garbage collection be forced?