我有一个C#(.NET 3.5)中的SomeSingleton
类和以下代码:
foo()
{
...
SomeSingleton.Instance.DoSomething();
...
}
我的问题是:何时Garbage Collector会收集这个Singleton对象?
附:SomeSingleton的代码:
private static SomeSingleton s_Instance = null;
public static SomeSingleton Instance
{
get
{
if (s_Instance == null)
{
lock (s_InstanceLock)
{
if (s_Instance == null)
{
s_Instance = new SomeSingleton();
}
}
}
return s_Instance;
}
}
感谢您的帮助! < p > < strong > 编辑 (附解释): < p>在Windows服务中,我有以下代码:
...
FirstSingleton.Instance.DoSomething();
...
public class FirstSingleton
{
(Instance part the same as in SomeSingleton)
public void DoSomething()
{
SomeSingleton.Instance.DoSomething();
}
}
我想要实现的目标是: 我不关心FirstSingleton会发生什么,但在第一次使用SomeSingleton时,它会启动计时器,因此只要我的服务在运行,就需要SomeSingleton存在(以便计时器可以每隔一段时间运行新线程)。
根据你的回答,我理解所有这些都会发生,因为对于我的FirstSingleton和SomeSingleton的引用是静态的,只有当服务停止时,单例才会被GC收集,我是正确的吗? :)
s_Instance
设置为null
并且没有任何其他相同的引用,否则它永远不会被垃圾回收。 - Sriram SakthivelIDisposable
,而是关于静态字段何时可以进行回收的。 - Lee