How to Avoid Running Two Processes Of The Same Application

This simple code example uses the class Mutex, which tests the many processes of an application that are executed. Provides a simple demonstration example in the Program.cs file and enter the code to prevent them being carried out two processes of the same application, then compile the project and start the application twice from the executable on the compilation. In the beginning start the application will start regularly, instead trying to start a new job in the same application you will see a message indicating that the application is already running.

But now we see how to use it in this example. Runs in the Program.cs file verification by the Mutex class.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Windows.Forms;  
  5. using System.Threading;  
  6. namespace MutexClassExample  
  7. {  
  8.     static class Program  
  9.     {  
  10.         static Mutex m;  
  11.         /// <Summary>  
  12.         /// Main entry point of the application.  
  13.         /// </ Summary>  
  14.         [STAThread]  
  15.         static void Main()  
  16.         {  
  17.             bool first = false;  
  18.             m = new Mutex(true, Application.ProductName.ToString(), first - out);  
  19.             if((first))  
  20.             {  
  21.                 Application.EnableVisualStyles();  
  22.                 Application.SetCompatibleTextRenderingDefault(false);  
  23.                 Application.Run(new Form1());  
  24.                 m.ReleaseMutex();  
  25.             }  
  26.             else  
  27.             {  
  28.                 MessageBox.Show("Application" + "" + Application.ProductName.ToString() + "" + "already running");  
  29.             }  
  30.         }  
  31.     }  
  32. }  
This line of code m = new Mutex (true, Application.ProductName.ToString (), first-out); requires three parameters. The first, initiallyOwned bool, True to the calling thread initial ownership of the mutex, false otherwise. The second parameter of type string, to which we must assign the name of our application, the last finally always of type bool, which assigns the result to the variable first. The latter determines if the application is already running or not depending on the state. In this case if we have the true message of application, it means it is already running, if false means that there was still a process of our application that was started.

Up Next
    Ebook Download
    View all
    View all