I'm trying to test C#'s GC behavior, in order to understand when exactly are objects collected. I've written this code, expecting it to output True and then false, but I see differing behaviors - on my machine and on Programiz it outputs True, True. On dotnetfiddle I get True, False.
WeakReference weakRef;
{
var obj = new object();
weakRef = new WeakReference(obj);
Assert.That(weakRef.IsAlive, Is.True);
obj = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.That(weakRef.IsAlive, Is.False);
Why do I see differing behaviors*? And when I get True, True - when will the strong reference be released, if not when a variable is nullified and out of scope?
- I assume that the sites use different compilers, but this seems basic enough that compilers should behave consistently on it.