Southmountain Ответов: 1

Почему эта слабая ссылка не собирает мусор, как ожидалось?


Я получил пример в интернете, чтобы проверить слабую ссылку. почему этот _weak не собирает мусор?

Что я уже пробовал:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestWeakReference2
{
 
    class Program
    {
        /// <summary>
        /// Points to data that can be garbage collected any time.
        /// </summary>
        //static WeakReference _weak;

        static void Main(string[] args)
        {
            // Assign the WeakReference.
            Dog sb = new Dog("Bowser");

            WeakReference _weak = new WeakReference(sb);

            // See if weak reference is alive.
            if (_weak.IsAlive)
            {
                Console.WriteLine((_weak.Target as Dog).ToString());
            }

            // Invoke GC.Collect.
            // ... If this is commented out, the next condition will evaluate true.
            sb = null;
            GC.Collect();

            Console.WriteLine(_weak.IsAlive.ToString());


            // Check alive.
            if (_weak.IsAlive)
            {
                Console.WriteLine("IsAlive");
            }
            else
            {
                Console.WriteLine("it is garbage collected!");
                
            }

            // Finish.
            Console.WriteLine("[Done]");
            Console.Read();
        }
    }


    public class Dog
    {
        private string name;

        public Dog() : this("noname")
        {

        }
        public Dog(string name)
        {
            this.name = name;
        }

    }

}

1 Ответов

Рейтинг:
7

Ashutosh Gpt

Я думаю, что условие if, добавленное для проверки alive, является здесь виновником того, что условие каким-то образом позволяет GC собирать здесь weakreferences.
приведенный ниже код должен работать для вас

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestWeakReference2
{
 
    class Program
    {
        /// <summary>
        /// Points to data that can be garbage collected any time.
        /// </summary>
        //static WeakReference _weak;

        static void Main(string[] args)
        {
            // Assign the WeakReference.
            Dog sb = new Dog("Bowser");

            WeakReference _weak = new WeakReference(sb);

            // See if weak reference is alive.
            if (_weak.IsAlive)
            {
                Console.WriteLine((_weak.Target as Dog).ToString());
                Console.WriteLine(_weak.IsAlive.ToString());
            }

            // Invoke GC.Collect.
            // ... If this is commented out, the next condition will evaluate true.
            sb = null;
            GC.Collect();

            Console.WriteLine(_weak.IsAlive.ToString());

            // Finish.
            Console.WriteLine("[Done]");
            Console.Read();
        }
    }


    public class Dog
    {
        private string name;

        public Dog() : this("noname")
        {

        }
        public Dog(string name)
        {
            this.name = name;
        }

    }

}


удалил условие if до alive после GC.collect и все должно быть в порядке