2012-01-16 82 views
4

我正在使用一個嵌套類創建的單例實例。這個實例包含了一些靜態集合,這些靜態集合在單例被丟棄時被清除,但問題是我得到了一個非空的單元的引用,這個單元沒有被正確地垃圾收集。如何以及何時處置/垃圾收集單例實例

我想知道WHEN和HOW如何完全處置和垃圾收集我的單例實例,以便在處理(並設置爲空)後再次查詢實例時創建新的實例。

我使用Singleton實例以下嵌套圖案:

public class SingletonClass : IDisposable 
{ 
    private List<string> _collection; 

    private SingletonClass() 
    { 
    } 

    public static SingletonClass Instance 
    { 
     get 
     { 
      return Nested.Instance; //line 1 - this line returns the non-null instance after dispose and setting the Singleton instance to null which is causing problems 
     } 
    } 

    private void Init() 
    { 
     _collection = new List<string>(); 
     //Add data to above collection 
    } 

    public void Dispose() 
    { 
     //Release collection 
     _collection.Clear(); 
     _collection = null; 
    } 

    class Nested 
    { 
     static Nested() 
     { 
      Instance = new SingletonClass(); 
      Instance.Init(); 
     } 

     internal static readonly SingletonClass Instance; 
    }  
} 

位於第1行的問題是,從客戶端類SingletonClass的處置之後,而SingletonClass實例保持非空的_collection對象變爲零即使在設置= null之後。

+0

中極穴單身人士是外面的代碼恰好看到一個實例。從來沒有兩個,也從不爲零(懶惰的實例化和應用程序結束清理)。如果你甚至可以考慮你的對象被替換的原因,你擁有的東西不能合法地成爲一個單例 - 任何保存到該對象的引用的代碼都將能夠看到兩個實例。 – cHao 2012-01-19 03:49:48

回答

4

你只需要實現System.IDisposable如果你符合以下基本要求:

這個接口的主要用途是釋放非託管資源。

然後,我會去該課程的析構函數,並在example中調用Dispose()

否則

垃圾收集器自動釋放分配給 管理對象時對象不再使用的內存。

(這不會是一個真正的單身的情況下,除非進程結束)

你可能會更好,如果你使用的是某事像這樣

class PseudoSingleton<T> 
    where T : new() 
{ 
    private readonly object _lock = new object(); 
    private T _instance; 

    public T Instance 
    { 
     get 
     { 
      lock (this._lock) 
      { 
       if (this._instance != null) 
       { 
        this._instance = new T(); 
       } 
       return this._instance; 
      } 
     } 
    } 
    public void Reset() 
    { 
     lock (this._lock) 
     { 
      this._instance = null; 
     } 
    } 
} 
+0

我懷疑析構函數是個好主意。 – abatishchev 2012-01-16 09:00:22

+0

不說msdn是聖盃,但有一個公平的機會是最佳實踐(沒有找到比這更好的東西) – 2012-01-16 09:01:41

+1

我也會試圖去析構 - 也不是一個好主意,但有時候 - 而這個問題似乎不是一個 - 它是正確的方法。 – 2012-01-16 09:07:16