Garbage Collection should have removed object but WeakReference.IsAlive still returning true

后端 未结 5 955
时光说笑
时光说笑 2020-12-06 05:50

I have a test that I expected to pass but the behavior of the Garbage Collector is not as I presumed:

[Test]
public void WeakReferenceTest2()
{
    var obj =         


        
5条回答
  •  心在旅途
    2020-12-06 06:21

    Could it be that the .Should() extension method is somehow hanging on to a reference? Or perhaps some other aspect of the test framework is causing this issue.

    (I'm posting this as an answer otherwise I can't easily post the code!)

    I have tried the following code, and it works as expected (Visual Studio 2012, .Net 4 build, debug and release, 32 bit and 64 bit, running on Windows 7, quad core processor):

    using System;
    
    namespace Demo
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                var obj = new object();
                var wRef = new WeakReference(obj);
    
                GC.Collect();
                obj = null;
                GC.Collect();
    
                Console.WriteLine(wRef.IsAlive); // Prints false.
                Console.ReadKey();
            }
        }
    }
    

    What happens when you try this code?

提交回复
热议问题