我有另一個C#理論問題,我希望我可以弄清楚一些,我已經看到了一些WeakReference示例,但他們從來沒有爲我工作,但我已經閱讀了一些人的評論和文章,樣本爲他們工作。我正在努力研究爲什麼這些樣本不適合我。我不知道它是GC.Collect()的非確定性行爲,我也在努力確定它是否適用。這是我目前工作的代碼,但我已經直接從說明這個概念,以及教程試了無數人:爲什麼我的WeakReference樣本不能工作?
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));
}
}
的WeakRerence總是還活着後,我調用GC.Collect()。我也嘗試添加對GC.WaitForFullGCComplete()和GC.WaitForPendingFinalizers()的調用,也沒有喜悅。
你的代碼按預期工作對我來說。 「** IsAlive」文本**不是正在爲我打印。 – Enigmativity