5

我正在使用从嵌套类创建的 Singleton 实例。此实例包含一些静态集合,这些集合在处理 Singleton 时会被清除,但问题是我得到了对非空处理 Singleton 的引用,它没有被正确地垃圾收集。

我想知道何时以及如何完全处置和垃圾收集我的 Singleton 实例,以便在处置(并设置为 null)之后再次查询该实例时创建一个新实例。

我对 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 后,_collection 对象变为 null,而 SingletonClass 实例即使在设置 = null 后仍保持非 null。

4

1 回答 1

6

System.IDisposable只有满足以下基本要求,您才需要实施:

该接口的主要用途是释放非托管资源。

然后我会去类的析构函数并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;
        }
    }
}
于 2012-01-16T08:57:04.797 回答