This is my code,the results and expected results. Why alive = true instead of false on second line?
Results:
weakRef.Target is alive = True, expected true because inst keep a hold on SomeClass.
weakRef.Target is alive = True, expected false, because there is no more ref on SomeClass.
Code:
public class SomeClass
{
public void DoSomething() { }
}
public static class GcHelper
{
public static void Collect()
{
// OK surely overkill but just to make sure. I will reduce it when everyting will be understood.
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
}
}
[TestMethod]
public void TestLifeOfObject()
{
Action callback;
var inst = new SomeClass();
var weakRef = new WeakReference<Action>(inst.DoSomething);
GcHelper.Collect();
Debug.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out callback)}, expected true because inst keep a hold on SomeClass.");
callback = null;
inst = null;
GcHelper.Collect();
Debug.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out callback)}, expected false, because there is no more ref on SomeClass.");
}