让 System.Timers.Timer
成为单例 volatile static
的成员有意义吗?
如果我在单例实例上下文中设置 _fooTimer
static
和/或 volatile
会有什么不同吗?
如果我不创建 _instance
static
会有什么不同吗?
EDIT2:我更正了代码示例并使其现在成为更好的 Singleton,没有不必要的静态或 volatile 字段并更改为 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()
...
}
最佳答案
通常,单例类中的唯一 静态变量是对单个实例的引用。然后,您将为该类型的剩余状态使用实例 变量。如果您将其设为静态,那么您甚至不需要创建该类的单个实例来使用计时器 - 但我期望您想要这样做无论如何。
我也会对使用 volatile
感到紧张...它几乎可以肯定并不完全是您认为的意思。我可能会使用 Interlocked
而是实现对变量的原子更新。
(请注意,根据 my article on the topic 有很多更好的实现方法。)
编辑:现在代码已更改以显示更多成员,这有点令人困惑。有一个 static 方法会使用 _counter
(一个实例变量)——大概是通过单例实例。基本上,这个类似乎还没有决定它是想成为一堆静态方法,还是一个单例实例。我建议您决定并让一切以一种或另一种方式访问,但不要混合使用。
关于c# - 单例中的静态/ volatile ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14586909/