Does it make sense to make a System.Timers.Timer member of a singleton volatile static?
Would it make any difference if I make the _fooTimer static and or volatile in singleton instance context?
Would it make any difference if I dont make _instance static?
EDIT2: I corrected the codesample and made it now ba better Singleton without unecessary static or volatile fields and changed to Interlock.Increment
public sealed class Foo
{
private static readonly object _syncRoot;
private int _counter;
private Timer _fooTimer;
private static Foo _instance;
private Foo()
{
_counter = 0;
_syncRoot = new object();
_fooTimer = new new Timer();
_fooTimer.Intervall = 3600000;
_fooTimer.Elapsed += new ElapsedEventHandler(LogFoo);
}
public static Foo Instance
{
get
{
lock(_syncRoot)
{
if (_instance == null)
{
_instance = new Foo();
}
}
return _instance;
}
}
private void LogFoo()
{
// write a logfile with _counter - then restart timer and set _counter to 0
}
public void Increment()
{
Interlocked.Increment(_counter);
}
}
public class UseTheFoo
{
// Foo.Instance.Increment()
...
}
Typically the only static variable in a singleton class is a reference to the single instance. You’d then use instance variables for the remaining state of the type. If you make it static then you don’t even need to create a single instance of the class to use the timer – but I would expect that you’d want to do so anyway.
I’d be nervous of using
volatile, too… it almost certainly doesn’t mean exactly what you think it means. I’d probably useInterlockedinstead to achieve atomic updates to the variable.(Note that there are plenty of better ways of implementing it, as per my article on the topic.)
EDIT: Now that the code has changed to show more members, it’s a bit confusing. There’s a static method which would use
_counter(an instance variable) – presumably via the singleton instance. Basically, the class doesn’t seem to have made up its mind about whether it wants to be a bunch of static methods, or a singleton instance. I suggest you decide and make everything accessible one way or the other, but not a mixture.