title: semaphore implementation for counting no. of instances currently running
body: <p>I am working on multi instance application. Is there any way in c# to know that how many instances are running currently.<br>I used one peice of code to count the window processes of my application name but that is not a good way.</p>
  
  <pre><code>string fileName = Process.GetCurrentProcess().MainModule.FileName;
  int count = 0;
  foreach (Process p in Process.GetProcesses())
  {
      try
       {
          if (p.MainModule.FileName == fileName)
          {
              count++;
          }
      }
      catch { }
  }
  
  MessageBox.Show("Total Instances Running are " + count);
  </code></pre>
  
  <p><br> Can it be done by using <em>semaphore</em> or some increment and decrement counter  that is incremented by one when new instance is created and decrement by one when a  instance closes.</p>