title: Windows Service application hangs
body: <p>Background:<br>
  - Running Window Server 2008 R2.<br>
  - The servers has been patched with all the recent updates.<br>
  - Server is running 5 services built in .NET 3.5 and all of these services use timers to check database on repeated basis (mostly every 10 seconds).<br>
  - These services are not CPU/RAM intensive.<br>
  - Server doesn't have any performace and resources issues or bottlenecks.<br></p>
  
  <p>For most of the time, everything works as expected, but from time to time, some (or all) services simply stop working. I'm logging all the app exceptions to file, but there are none when it comes to failure. There is also no error in the event logger and the Services manager treats the services as running. I have to stop the services and start them once again to restore the functionality.</p>
  
  <p>This behavior is unpredictable, sometimes it takes a week or a month before it stops working. Also, sometimes the services "dies" all together or only some of them at the same time.</p>
  
  <p>Only thing that crossed my mind is the Timer object. I've been using the System.Timers.Timer and found several forum threads stating it is unreliable as the garbage collector may free the instance. I've tried retaining it using GC.KeepAlive() to no avail. I've followed a few suggestion on moving System.Timers.Timer to System.Threading.Timer but this didn't make any difference either.</p>
  
  <p>Right at the moment, I'm desperate to find out the source of this behavior. Is there any known similar issue? How can I debug it when there is not exception raised and the event log is silent too?</p>
  
  <p>Thank you for any advice that may lead to any solution.</p>
  
  <p>UPDATE: Including the bare-boned code of the current state:</p>
  
  <pre><code>private System.Threading.Timer timerPublish = null;
  private bool timerDelegateMethodRunning = false;
  
  protected override void OnStart(string[] args)
  {
      SetupTimer();
  }
  
  protected override void OnStop()
  {
      if (timerPublish != null)
      {
          timerPublish.Dispose();
      }
  }
  
  public void SetupTimer()
  {
      if (timerPublish != null)
      {
          timerPublish.Dispose();
      }
      TimerCallback callbackMethod = new TimerCallback(this.timerPublish_Elapsed);
      timerPublish = new System.Threading.Timer(callbackMethod, null, 5000, 5000);
  }
  
  void timerPublish_Elapsed(Object stateInfo)
  {
      if (timerDelegateMethodRunning)
      {
          return;
      }
      timerDelegateMethodRunning = true;
  
      try
      {
          // Processing code here
      }
      finally
      {
          timerDelegateMethodRunning = false;
      }
  }
  </code></pre>
  
  <p><br><br></p>
  
  <p>UPDATE2: Thank you guys for your insights and advices. I'll try to debug the services on the production server once the issue happens again. I'll report back as soon as I have anything new (probably in several weeks).</p>