如何处置/垃圾收集单例实例
我正在使用从嵌套类创建的单例实例。该实例保存了一些静态集合,这些静态集合在单例被处置时被清除,但问题是我得到了对非空处置单例的引用,而该单例未正确进行垃圾收集。
我想知道如何完全处置和垃圾收集我的 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。
I am using a Singleton instance created out of a nested class. This instance holds some static collections which are cleared when the Singleton is disposed, but the problem is I get a reference to non-null disposed Singleton which is not properly garbage collected.
I would like to know how to completely dispose and garbage collect my Singleton instance so that when the instance is queried again after dispose (and setting to null) a new Instance is created.
I am using the following nested pattern for Singleton instance:
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;
}
}
The problem at line 1 is that after dispose of SingletonClass from client class, the _collection object becomes null while the SingletonClass instance remains non-null even after setting = null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您满足以下基本要求,则只需实现
System.IDisposable
:然后我会寻找类的析构函数并在 Microsoft 文档示例。
否则
(真正的单例不会出现这种情况,除非过程结束)
如果您使用这样的东西,您可能会更好
You'll only need to implement
System.IDisposable
if you fulfill following basic requirement:Then I would go for the destructor of the class and call
Dispose()
in the Microsoft Docs Example.Otherwise
(which won't be the case with a real singleton, unless the process ends)
You may be better off, if you are using sth like this