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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Windows.Forms;
- using System.Threading;
- namespace MutexClassExample
- {
- static class Program
- {
- static Mutex m;
-
-
-
- [STAThread]
- static void Main()
- {
- bool first = false;
- m = new Mutex(true, Application.ProductName.ToString(), first - out);
- if((first))
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new Form1());
- m.ReleaseMutex();
- }
- else
- {
- MessageBox.Show("Application" + "" + Application.ProductName.ToString() + "" + "already running");
- }
- }
- }
- }
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.