How to Restrict a Program to Single Instance in .NET?

Assume that you have created a windows application called CustomCalc.exe (Customized Calculator) and it is installed in a machine. Each time the User clicks CustomCalc.exe, an instance gets opened. What if the User clicks CustomCalc.exe ten times continuously? Ten different instances get open, but User is really going to use only one instance. You can avoid this scenario by restricting the User to open only one instance of your application at a time. If User tries to open a second instance, then you can prompt a message to convey that an instance is already open.

Is this quite interesting? Then read through this article to know how to implement this concept in two different ways in your program. For your need, code samples are provided here in C# and VB.NET

Code Sample in C#:

In C#, you can implement this single instance logic in two different ways.

Solution 1: Using Process Table

static void Main()
{
Process [ ] activeProcess = Process.GetProcessByName(Process.GetCurrentProcess.ProcessName);
if (activeProcess.Length ==1 )
{
Application.Run(new MainForm());
}
else
{
MessageBox.show(“An instance of this application is already Open”);
}
}

Here Process.GetCurrentProcess().ProcessName creates a new process which is going to be the current process. Check if this process is already running by using GetProcessesByName function. This function returns more than one process if your application is already running.

If there are no instances open, then this function will return only one process which is the current process that you created. So the length of activeProcess gives you the answer. If it is one, then you can very well create an instance of your application. If length is more than one, then you can prompt corresponding message.

This solution is commonly used. But the drawback is that: if many processes are running, then GetProcessByName function has to read each of them. This is very time consuming and your application might slow down.

Solution 2: Using Mutex Method

Mutex is an object provided by operating system. It is used to establish communication among processes. Mutex can be acquired by only one thread at a time. Another thread can acquire it only when it is released by the earlier thread. In your main form you can write code to create and get hold of a mutex with specific name. If you can create it, then this is going to be first instance and you can open it. If the mutex is already acquired by another thread, then it means that another instance of your application is already open. Hence you can deny to instantiate your application.

You can accomplish this logic in your application by using the following piece of code:

public class testMutex{
static Mutex mutexInstance;

public static void Main(String args[]){
bool instanceCheck;
mutexInstance = new System.Threading.Mutex(true, "testSingleInstance", out
instanceCheck);
if (instanceCheck){
Application.Run(new FormApp ()); //FormApp is the name of the form
}
else{
MessageBox.Show("An instance of this application is already Open");
return;
}
GC.KeepAlive(mutexInstance);
}

If the mutexInstance is garbage collected then this logic will not work. To ensure that it is active, GC.KeepAlive statement is used.

Code Sample in VB.NET:

You can use the above two logics in VB.NET as well to restrict your application to single instance.

Solution 1: Using Process Table

The approach is same as that of Solution 1 mentioned above. The Syntax alone varies.

Private Sub MainForm_Load(Byal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length() <> 1
Then
MessageBox.Show("An instance of this application is already Open",
MessageBoxButtons.OK, MessageBoxIcon.Warning));
End
End If
End Sub

Solution 2: Using Mutex Method

Mutex concept is same as that of C#. Syntax alone varies. The Code is mentioned below:

Dim mutexInstance As Mutex
Dim instanceCheck As Boolean
mutexInstance = _New Mutex(True, "testSingleInstance”, instanceCheck)
If instanceCheck then
//write code to open the instance of your application
else
MessageBox.Show("An instance of this application is already Open",
MessageBoxButtons.OK, MessageBoxIcon.Warning));
End
End If
mutexInstance.Close()

| Additional Ways of Ensuring Security in .NET | Memory Lifecycle in .NET – An Overview | Few Best Coding Practices for ASP .NET | Handling Session Efficiently Using SQLSERVER State Management in .NET | How to Restrict a Program to Single Instance in .NET? | How to Use Structured Exception Handling in .NET | Understanding Boxing Versus Unboxing in .NET | Understanding Different Levels of Security in .NET | Understanding the Disadvantages of Memory Management in .NET | Using Membership API for Secured Coding in .NET |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.