Category : C# | Author : Chtiwi Malek | First posted : 3/14/2012 | Updated : 12/6/2012
Tags : .net, c#, asp.net, framework, clr, instance, application, wcf
How to force running only one instance of your application in C#

How to force running only one instance of your application in C#

If you do not want to allow the user to run multiple instances of your application, here‘s how to do that using the Mutex class from System.Threading :
        // Setup a unique Name for your Application
        static Mutex mutex = new Mutex(false, "My_Unique_App_ID");

        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            // Delay 3 seconds to be sure that there is no other instance running
            if (!mutex.WaitOne(TimeSpan.FromSeconds(3), false))
            {
                MessageBox.Show("Another instance of this application is already running");
                return;
            }

            try
            {
                // There is no other instances running
                // Launch the application
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
The Mutex will be released when the application ends, but even if the application terminates without releasing the Mutex, it will be automatically released by the .net framework.
Comments & Opinions :
Thanks
thank you, it helped me a lot
- by Joe on 3/16/2012
tubble
tae vs tubble
jayjay supot tumatae sa jaryo
- by Tae on 10/14/2012
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :