I want to test references to objects stored improperly, and wrote a test that always failed. I simplified the test for the following behavior:
[Test] public void ScopesAreNotLeaking() { WeakReference weakRef; Stub scope = null; using (scope = new Stub()) { weakRef = new WeakReference(scope); } scope = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.That(weakRef.Target, Is.Null); }
However, this test, which does the same without use, passes:
[Test] public void ScopesAreNotLeaking() { WeakReference weakRef; Stub scope = new Stub(); weakRef = new WeakReference(scope); scope = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.That(weakRef.Target, Is.Null); }
The stub class used is quite simple:
class Stub : IDisposable { public void Dispose() {} }
Can someone please explain to me that the behavior or, even better, have an idea how to make sure that the object receives garbage collection?
PS: Take me if you had a similar question before. I studied only the questions that are used in the title.
source share