The garbage collector will not collect an object created using

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.

+6
source share
4 answers

I suspect there may be a locale entered by the using statement. Use ildasm to check if all references in the function to the object are really cleared before calling GC.Collect . Also try putting the usage bit in a separate function that returns a weak link.

+2
source

use is not intended to force garbage collection, but to provide a utility call. Dispose allows you to free non-garbage resources such as file descriptors. Garbage collection occurs when C # is good and ready.

+5
source

Mark and GC sweep, as in .NET, are not deterministic. Even if GC.Collect() is called, there is no guarantee that it really does.

In addition, the use clause has nothing to do with garbage collection. If just calls Dispose () on the target.

+1
source

Your two tests are not identical. At the end of the using statement, the Dispose resource method is called; it is not set to null. Calling Dispose does not necessarily invoke the destructor.

+1
source

Source: https://habr.com/ru/post/889878/


All Articles