How to run only a Single Instance of the Application using Windows Forms

Posted by: Suprotim Agarwal , on 5/4/2008, in Category WinForms & WinRT
Views: 52824
Abstract: If you are looking out for a quick solution to prevent the user from opening up multiple instances of the application, this article is was for you. We will explore how to use Mutex to check for the running instance of the application and prevent creation of multiple instances.
How to run only a Single Instance of the Application using Windows Forms
 
If you are looking out for a quick solution to prevent the user from opening up multiple instances of the application, this article is was for you. We will explore how to use Mutex to check for the running instance of the application and prevent creation of multiple instances.
Mutex is a synchronization mechanism that prevents simultaneous use of a common resource, by multiple threads. When multiple threads access a shared resource, Mutex grants the access to only one thread at a time. It is only after the first thread releases the Mutex, the second thread is able to take access to the resource.  Let us see how we can use Mutex to open up only one instance of the application at a time. Follow these steps:
Step 1: Create a new windows form project and open the Program.cs file. The code will be similar to the following:
C#
   static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
VB.NET
   Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Private Sub New()
            End Sub
            <STAThread> _
            Shared Sub Main()
                  Application.EnableVisualStyles()
                  Application.SetCompatibleTextRenderingDefault(False)
                  Application.Run(New Form1())
            End Sub
   End Class
Step 2: We will change the code shown above to use Mutex and restrict the access to the form creation to a single thread. This will in turn force other threads to wait until the Mutex is released by the owner thread.
When you initialize a Mutex, you can assign it a name and a Boolean value(to its constructor). The Boolean value determines if the calling thread takes over the ownership of the Mutex. So the first time the application starts, the variable ‘instanceCountOne’ is set to true to indicate that the calling thread has taken over the ownership.
Now the next time, when the user attempts to run the application again, the name ‘MyRunningApp’ is checked to see if the Mutex already exists at the time of the Mutex initialization. If the name exists, then that Mutex object instance is returned. So the variable ‘instanceCountOne’ remains false and thus the user gets a message stating “An application instance is already running”
Here’s how the code will look like:
C#
   static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            bool instanceCountOne = false;
 
            using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
            {
                if (instanceCountOne)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    mtex.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("An application instance is already running");
                }
            }
        }
    }
VB.NET
   Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Private Sub New()
            End Sub
            <STAThread> _
            Shared Sub Main()
                  Dim instanceCountOne As Boolean = False
 
                  Using mtex As Mutex = New Mutex(True, "MyRunningApp", instanceCountOne)
                        If instanceCountOne Then
                              Application.EnableVisualStyles()
                              Application.SetCompatibleTextRenderingDefault(False)
                              Application.Run(New Form1())
                              mtex.ReleaseMutex()
                        Else
                              MessageBox.Show("An application instance is already running")
                        End If
                  End Using
            End Sub
   End Class
Well that’s it. Using the code shown above, you can now prevent multiple instances of the application from running. Just a word of caution though. The process of checking up the mutex name can be a little time consuming.I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Avinash on Thursday, May 8, 2008 2:16 AM
Thanks for this article  Suprotim and i am unable to find the program.vb file for vb.net ? its not displayed in my project....
Comment posted by SDO on Friday, July 11, 2008 3:16 AM
Hi,

Is it ok with Terminal Server ? If application is running for one user, it cannot be run by another.
Comment posted by John on Friday, July 11, 2008 4:13 AM
How about displaying the current active instance instead of telling the user a instance is already running?
Comment posted by IJsbrand on Friday, July 11, 2008 10:36 AM
What if your program crashes? The mutex is never released, so you are unable to restart your application, isn't it?
Comment posted by Suprotim Agarwal on Wednesday, July 16, 2008 1:56 PM
John,IJsbrand: I had discussed this point over here:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2426414&SiteID=1
Comment posted by Digimist on Saturday, July 26, 2008 12:43 AM
Its great that you show VB as well as c# Thanks
Comment posted by reivilos on Thursday, July 31, 2008 8:58 AM
Should not use string such as "MyRunningApp" for mutex name.
What is you want to use an app written by someone that read this thread ?????
Better use low-collision strings such as GUID.

http://msdn.microsoft.com/en-us/library/system.guid.aspx
Comment posted by Suprotim Agarwal on Thursday, July 31, 2008 10:00 AM
reivilos: I appreciate your comments and also agree that replacing strings with GUID is a good practice.
Comment posted by abkasoft on Sunday, December 18, 2011 10:00 AM
sounds good, but you forgot to import System.Threading to Mutex.
thanks all in all.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook