title: C# timer and thread safety
body: <p>I have a C# class with an array of objects, each object representing an open connection to an external device.  The connections time out by default after n idle hours which I want to avoid.  I plan to make use of a timer that trips every n-2 idle hours, with a callback that invokes a method to touch each object and effectively reset the timeout.</p>
  
  <p>The class needs to be usable in both Windows forms and non forms-based projects, hence I am considering using System.Timers.Timer and a lock to restrict any other thread from accessing the array during timeout reset.</p>
  
  <p>Using a timer introduces thread safety implications, e.g. if one of the objects is destructed in between the timer callback determining that an object exists and resetting its timeout, there will be an attempt to read uninitialised memory.  However, my problem is that the array is accessed in a number of places in the class.  The lock should prevent all access to the array while the timer callback is in progress as follows: </p>
  
  <pre><code>class MyClass
  {
      private System.Timers.Timer timer;
      private object locker = new object();
  
      public void Run()
      {
          timer = new System.Timers.Timer();
          timer.Interval = 21600000;  //6 hours
          timer.Elapsed += AccessArrayCallback;
          timer.Start();
      }
  
      public void AccessArrayCallback(object sender, EventArgs e)
      {
  
          timer.Enabled = false;
          lock (locker)
          {
              /*  
  
              if (called by timer) 
              {  
                  iterate through array and reset connections;
              }
              else 
              {
                  Call appropriate function that reads/writes array using EventArgs delegate   
              }
  
              */
          }
          timer.Enabled = true;
  
      }
  }
  </code></pre>
  
  <p>A few questions before I continue with this approach: </p>
  
  <ol>
  <li><p>Is there an established pattern/more elegant approach to this kind of problem?</p></li>
  <li><p>Is it correct to use a delegate in EventArgs?  Any other method in the class requiring access to the array will call the callback and populate EventArgs appropriately.</p></li>
  </ol>
  
  <p>Thanks in advance.</p>