title: C# application close the first instance of itself
body: <p>I know how to make sure that I run only one instance of an application at a time:
  <a href="https://stackoverflow.com/questions/6392031/c-sharp-how-to-check-if-another-instance-of-the-application-is-running">How to check if another instance of the application is running</a></p>
  
  <p>But... How can I make sure that when a second instance is started, the first instance will be closed (instead of just exiting the 2nd one which is usually done). And preferably waiting for it to be fully closed.</p>
  
  <p>If more than 2 instances are started simultaneously then only the last one should be allowed to 'live'.</p>
  
  <p>I got it (thanks you all the answers). My solution below:</p>
  
  <pre><code>        #region Kill other running processes of this application
          List&lt;Process&gt; processes = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).ToList();
          if (processes.Count &gt; 1)
          {
              processes.Sort((x, y) =&gt; DateTime.Compare(x.StartTime, y.StartTime));
              for (int i = 0; i &lt; processes.Count - 1; i++)
              {
                  processes[i].CloseMainWindow();
                  processes[i].WaitForExit();
              }
          }
          #endregion
  
          Console.WriteLine(string.Format("{0}:{1}", DateTime.Now.Minute, DateTime.Now.Second));
          Console.ReadLine();
  </code></pre>