我在C#(.NET 3.5,如果它事项)和一些代码SomeSingleton
类:垃圾回收器什么时候会收集一个Singleton?
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启动定时器首先使用它,所以我需要SomeSingleton存在(所以定时器可以在每个时间段运行新线程),只要我的服务正在运行。
从我的理解你的答案所有这些将会发生,因为我的FirstSingleton和SomeSingleton的引用是静态的,并且在服务停止之前单身人士不会被GC收集,对吗? :)
相信其在应用程序终止时(沿与其余静态值一起)(假设引用未被删除) – Sayse
除非和直到将's_Instance'设置为'null'并且您没有任何其他相同的引用 –
它永远不会被垃圾收集因为你的代码很关心:从不。这对你并不重要。当你担心Dispose(!= collect)时,询问一下。 –