Probar / verificar una referencia débil
Me gustaría verificar que el código establezca unaWeakReference
no contiene accidentalmente una referencia fuerte al objeto referenciado. (Aquí estáun ejempl de cómo es fácil hacer esto accidentalmente).
¿Parece esta la mejor manera de buscar referencias fuertes inadvertidas?
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);