c# - 单例中的静态/ volatile

标签 c#

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/

相关文章:

c# - 视频转换时间过长

c# - C# 查询三张表

c# - 在屏幕上检索凝视坐标

c# - 在 C# 中合并和更新两个列表

c# - Windows Phone 8.1 POST x-www-form-urlencoded 不工作

c# - 覆盖文件最快的方法是什么?

c# - 调试从 csrun.exe 开始的 Azure Web 角色

c# - 在控制台应用程序中等待异步操作后,WCF 客户端挂起任何操作

c# - LINQ 两个 Where 子句

c# - 将 .eot 嵌入式字体与 Net Framework WebBrowser 控件一起使用