简体   繁体   中英

Why won't my WeakReference sample work?

I have another C# theory question I am hoping I can get some clarity on, I have seen a few WeakReference samples around but they never work for me but I've read in some people's comments and articles that the samples work for them. I am battling to find out why these samples are not working for me. I can't tell if it is non-deterministic behavior of GC.Collect(), which I'm also battling to establish if that is even applicable. This is the code I'm working on at the moment but I have tried numerous others directly from tutorials that illustrate the concept as well:

class Program
{
    static WeakReference _weak;

    static void Main(string[] args)
    {
        _weak = new WeakReference(new WeakClass { Name = "Matthew" });

        if (_weak.IsAlive)
        {
            Console.WriteLine((_weak.Target as WeakClass).ToString());
        }

        GC.Collect();

        if (_weak.IsAlive)
        {
            Console.WriteLine("IsAlive"); // This is always being printed when, according to the articles, it shouldn't be
        }

        Console.WriteLine("[Done]");
        Console.Read();
    }
}
class WeakClass
{
    public string Name { get; set; }
    public override string ToString()
    {
        return this.Name;
    }
    ~WeakClass()
    {
        Console.WriteLine(string.Format("{0} got destructed...", this.Name));
    }
}

The WeakRerence is always still alive after I call GC.Collect(). I've also tried adding calls to GC.WaitForFullGCComplete() and GC.WaitForPendingFinalizers() as well with no joy.

I'm assuming you're running this in Debug mode , where the runtime isn't as eager to collect unreferenced variables and doesn't optimize your code in order for you to be able to debug your application.

If you compile and run this same code in Release mode , you'll usually see that the second call to WeakReference.IsAlive will yield false after GC.Collect .

This is what I see running LINQPad 5 in Release Mode:

Matthew
[Done]
Matthew got destructed...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM