title: Writing a sync application using Windows Service to process files in Parallel
body: <p>I have a folder on my windows server, where people will be uploading CSV files to, <code>C:\Uploads</code>.</p>
  
  <p>I want to write a simple windows service application that will scan this uploads folder (every 5 seconds) and collect the files in and process them in parallel (Thread /per File?). However, the main scanning process should not overlap, i.e. locking is required.</p>
  
  <p>So, I was experimenting with it like this:
  <em>I am aware this is not windows service code, it's a console app to test ideas...</em></p>
  
  <p><strong>Updated Code, based on dcastro's reply</strong></p>
  
  <pre><code>class Program
  {
      static Timer _InternalTimer;
      static Object _SyncLock = new Object();
  
      static void Main(string[] args)
      {
          _InternalTimer = new Timer(InitProcess, null, 0, 5000); // Sync cycle is every 5 sec
  
          Console.ReadKey();
      }
  
      private static void InitProcess(Object state)
      {
          ConsoleLog("Starting Process");
          StartProcess();
      }
  
      static void StartProcess()
      {
          bool lockTaken = false;
          try
          {
              Monitor.TryEnter(_SyncLock, ref lockTaken);
              if (lockTaken)
              {
                  ConsoleLog("Lock Acquired. Doing some dummy work...");
  
                  List&lt;string&gt; fileList = new List&lt;string&gt;()
                  {
                      "fileA.csv",
                      "fileB.csv"
                  };
  
                  Parallel.ForEach(fileList, (string fileName) =&gt;
                  {
                      ConsoleLog("Processing File: " + fileName);
                      Thread.Sleep(10000); // 10 sec to process each file
                  });
  
                  GC.Collect();
              }
              else
                  ConsoleLog("Sync Is Busy, Skipping Cycle");
          }
          finally
          {
              if (lockTaken)
                  Monitor.Exit(_SyncLock);
          }
      }
  
      static void ConsoleLog(String Message)
      {
          Console.WriteLine("[{0}]: {1}",
              DateTime.UtcNow.ToString("HH:mm:ss tt"),
              Message);
      }
  }
  </code></pre>
  
  <p>When it runs, it looks like this:</p>
  
  <p><img src="https://i.imgur.com/GH1VYxr.png" alt="enter image description here"></p>
  
  <p>Does this look right? Any help/tips on improving this will be much appreciated.</p>