System.Timers.Timer
成为单例的成员有意义volatile static
吗?
如果我在单例实例上下文中进行_fooTimer
static
and or会有什么不同吗?volatile
如果我不做会有什么不同_instance
static
吗?
EDIT2:我更正了代码示例,现在使它变得更好单例,没有不必要的静态或易失性字段,并更改为 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()
...
}