Pet*_*ter 4 .net c# singleton garbage-collection
我SomeSingleton在C#中有一些类(如果重要,则为.NET 3.5)和代码:
foo()
{
...
SomeSingleton.Instance.DoSomething();
...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:垃圾收集器什么时候会收集这个Singleton对象?
ps: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;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢帮助!
编辑(附说明):
在Widnows服务中我有代码:
...
FirstSingleton.Instance.DoSomething();
...
public class FirstSingleton
{
(Instance part the same as in SomeSingleton)
public void DoSomething()
{
SomeSingleton.Instance.DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的目标:我不关心FirstSingleton会发生什么,但SomeSingleton首先使用它启动Timer,所以我需要SomeSingleton存在(所以定时器可以在每个时间段运行新线程),只要我的服务是运行.
正如我从你的答案中理解的那样,所有这一切都会发生,因为对我的FirstSingleton和SomeSingleton的引用是静态的,并且在服务停止之前GC不会收集单身人士,我是对的吗?:)
| 归档时间: |
|
| 查看次数: |
3504 次 |
| 最近记录: |