gpt4 book ai didi

c# - 如何处理/垃圾收集单例实例

转载 作者:太空狗 更新时间:2023-10-29 23:25:34 25 4
gpt4 key购买 nike

我正在使用从嵌套类创建的单例实例。此实例包含一些静态集合,这些集合在处置 Singleton 时被清除,但问题是我得到了对非 null 处置 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。

最佳答案

如果满足以下基本要求,您只需实现 System.IDisposable:

The primary use of this interface is to release unmanaged resources.

然后我将寻找类的析构函数并在 Microsoft Docs Example 中调用 Dispose() .

否则

The garbage collector automatically releases the memory allocated to amanaged object when that object is no longer used.

(除非进程结束,否则真正的单例不会出现这种情况)

如果你像这样使用某物,你可能会过得更好

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;
}
}
}

关于c# - 如何处理/垃圾收集单例实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com