<分区>
我在 C# 中有一些 SomeSingleton
类(如果重要的话是 .NET 3.5)和代码:
foo()
{
...
SomeSingleton.Instance.DoSomething();
...
}
我的问题是:垃圾收集器什么时候收集这个 Singleton 对象?
p.s: 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;
}
}
感谢您的帮助!
编辑(附解释):
在 Widnows 服务中我有代码:
...
FirstSingleton.Instance.DoSomething();
...
public class FirstSingleton
{
(Instance part the same as in SomeSingleton)
public void DoSomething()
{
SomeSingleton.Instance.DoSomething();
}
}
我想要实现的目标: 我不关心 FirstSingleton 会发生什么,但是 SomeSingleton 会在第一次使用它时启动 Timer,所以只要我的服务正在运行,我就需要 SomeSingleton 存在(这样计时器可以在每个时间段运行新线程)。
根据您的回答,我了解到所有这些都会发生,因为对我的 FirstSingleton 和 SomeSingleton 的引用是静态的,并且在服务停止之前 GC 不会收集单例,对吗? :)