다음을 통해 공유


C#: How to prevent two processes running the same application

With this example, we show how to avoid the execution of two processes of the same application. With vb net we can mark the box 'make single-instance' in the properties section of the project application. This option is not available in an application running with C #, and it comes in handy here that the Mutex class.

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Windows.Forms;
 using System.Threading;
  
namespace MutexClassExample
 {
     static class  Program
     {
         static Mutex m;
         /// <summary>
         /// Punto di ingresso principale dell'applicazione.
         /// </summary>
         [STAThread]
         static void  Main()
         {
             bool first = false;
             m = new  Mutex(true, Application.ProductName.ToString(), out  first);
             if ((first))
             {
                 Application.EnableVisualStyles();
                 Application.SetCompatibleTextRenderingDefault(false);
                 Application.Run(new Form1());
                 m.ReleaseMutex();
             }
             else
             {
               MessageBox.Show("Application" + " "  + Application.ProductName.ToString() + " "  +"already running");
             }
         }
     }
 }