By default, .NET windows forms applications generally allow multiple instances of the same application to be started on the same machine. However, if two or more threads attempt to access a shared resource such as shared memory at the same time, concurrency issues may occur. And in a production environment, this might result in data inconsistency or inaccuracy.
This problem can be avoided using mutual exclusion (Mutex) to ensure that simultaneous instances of the same program cannot be run.
The code below demonstrates how this may be done.
static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "DemoApp", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("The Application Is Already Running", "DemoApp", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
The message shown in the picture above is displayed to the user if he attempts to start an instance of the program when another instance of the same program is already running.
very good its working
Will it work when application is installed on network and multiple instance has been instantiated.
Your example is working when application in installed on local but I tried it on sharing path and there it is failing.
Please suggest me if you have any solution.
Thanks
Hi Chanchal,
The mutex implementation described here will not work as you want across network computers.
To do the sort of mutex you want, you’ll need some form of communication between your clients and a central point. A database would be a good “central point”. Does your application already use a database?
Thanks.