Thursday, May 10, 2012

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#
   using system.Threading;
   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.

No comments:

Post a Comment