2016-03-06 17 views
2

我有另一個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()的調用,也沒有喜悅。

+0

你的代碼按預期工作對我來說。 「** IsAlive」文本**不是正在爲我打印。 – Enigmativity

回答

3

我假設你正在運行調試模式,其中運行時並不急於收集未引用的變量,也未優化代碼以便能夠調試應用程序。

如果編譯和發佈模式執行與此相同的代碼,你會通常看到,到WeakReference.IsAlive第二個電話會GC.Collect後產生錯誤的。

這是我所看到的在釋放模式運行LINQPad 5:

Matthew 
[Done] 
Matthew got destructed... 
+0

非常感謝。我剛剛嘗試在發佈模式下構建,並從bin \ Release文件夾運行,現在可以運行。這讓我一陣沮喪,非常感謝。出於興趣的緣故,在調試模式下運行時沒有一致性的原因是什麼,或者這只是我必須意識到要始終在發佈模式下測試的原因嗎? – macmatthew

+0

@macmatthew我建議你閱讀[Debug/Release](http://stackoverflow.com/questions/367884/what-is-the-difference-between-debug-and-release-in-visual-studio)以便獲得更多關於兩者之間差異的見解。這不是關於不一致性,而是調試模式,就像它的名稱所說的那樣,可以幫助您調試代碼。 –

+0

非常感謝你的建議,我一定會閱讀那篇文章!再次感謝幫助我。我的研究沒有任何進展。 – macmatthew

相關問題