Friday, July 3, 2009

Mutex - Restrict Single Instance of .Net application

you may want to ensure that only one copy of your .exe runs at a time.

Many persons are using GetProcessesByName () method to determine whether the process is running already or not.

But the draw back of the method is if the number of processes running is high, it will be time consuming process as we need to get all processes list and check it.

The simplest way is to use Mutex.

use the System.Threading.Mutex class . To use this technique, generate a named Mutex at the application’s entry point, and lock it. When a second instance is started, it will fail since it can’t be locked.


put this code in your project’s entry point:

Dim mut As System.Threading.Mutex = _
New System.Threading.Mutex(False, Application.ProductName)

Dim running As Boolean = Not mut.WaitOne(0, False)
'If already running
If running Then
End If

No comments:

Post a Comment