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
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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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
The Absolutely Awesome jQuery CookBook.
Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn