title: Using WaitHandle.WaitOne
body: <p>I am attempting to create a windows service that polls every 5 minutes a system and checks for some action that needs done. I have read up on <code>WaitHandles</code> and their usefulness in this area, but need to understand how this works.</p>
  
  <p>See code below:</p>
  
  <pre><code>public partial class PollingService : ServiceBase
  {
      private CancellationTokenSource cancelToken = new CancellationTokenSource();
      private Task mainTask = null;
      public PollingService()
      {
          InitializeComponent();  
      }
      protected override void OnStart(string[] args)
      {   
          mainTask = new Task(pollInterval, cancelToken.Token, TaskCreationOptions.LongRunning);
          mainTask.Start();
      }
      public void pollInterval()
      {
          CancellationToken cancel = cancelToken.Token;
          TimeSpan interval = TimeSpan.FromMinutes(5);
          while (!cancel.IsCancellationRequested &amp;&amp; !cancel.WaitHandle.WaitOne(interval))
          {
              if (cancel.IsCancellationRequested)
              {
                  break;
              }
              EventLog.WriteEntry("*-HEY MAN I'M POLLNG HERE!!-*");
              //Polling code goes here. Checks periodically IsCancellationRequested
          }
      }
      protected override void OnStop()
      {
          cancelToken.Cancel();
          mainTask.Wait();
      }
  }
  </code></pre>
  
  <p>The above code seems like something that should work from my research, but I don't understand the <code>!cancel.WaitHandle.WaitOne(interval)</code> portion. How does this keep the loop going with a wait every five minutes? I need to understand this part of the code to complete my script, or to know if I am completely wrong in my use of the WaitHandle.</p>
  
  <p>This was where I got the idea: <a href="https://stackoverflow.com/questions/19691022/creating-a-c-sharp-windows-service-to-poll-a-database">Creating a c# windows service to poll a database</a></p>