Static / unstable in singleton

Does it make sense to make a System.Timers.Timersingleton element volatile static?

Will it matter if I create _fooTimer staticand or volatilein the context of a singleton instance?

Would it matter if I did not _instance static?

EDIT2: I adjusted the code and made it better than Singleton now without unnecessary static or mutable fields and was 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()         

     ...
}
+5
source share
2 answers

. . , , , .

, volatile... , , . Interlocked , .

( , , .)

EDIT: , , , . , _counter ( ) - singleton. , , , , singleton. , .

+10

CLR:

public static class Foo
{
  private static Timer _fooTimer;

  static Foo()
  {
     _fooTimer = new Timer();
  }
}
+2

All Articles