I have some SomeSingleton
class in C# (.NET 3.5 if it matters) and code:
foo()
{
...
SomeSingleton.Instance.DoSomething();
...
}
My question is: when will Garbage Collector collect this Singleton object?
p.s: code of 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;
}
}
Thanks for help!
EDIT (with explanation):
In Widnows Service I have code:
...
FirstSingleton.Instance.DoSomething();
...
public class FirstSingleton
{
(Instance part the same as in SomeSingleton)
public void DoSomething()
{
SomeSingleton.Instance.DoSomething();
}
}
What I want to achieve: I do not care what happens with FirstSingleton, but SomeSingleton starts Timer with first use of it, so I need SomeSingleton to exist (so the timer can run new thread every period of time) as long as my service is running.
As I understand from your answers all of that will happen because reference to my FirstSingleton and SomeSingleton is static, and singletons will not be collected by GC until service stops, am I right? :)