Ben Gribaudo Ben Gribaudo - 2 months ago 19
C# Question

Testing/Verifying a WeakReference

I'd like to verify that code setting up a

does not accidentally hold a strong reference to the referenced object. (Here's an example of how it is easy to accidentally do this.)

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.
Assert.Equals(wr.Target, testObject);

// Force disposal of testObj;
testObj = null;
GC.Collect();
// If no strong references are left to the wr.Target, wr.IsAlive will return false.
Assert.False(wr.IsAlive);

Answer

I got in touch with Microsoft about this and learned/confirmed that:

  • GC.Collect() forces a blocking garbage collection.
  • When 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?

Comments