Почему эта слабая ссылка не собирает мусор, как ожидалось?
Я получил пример в интернете, чтобы проверить слабую ссылку. почему этот _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; } } }