Reputation: 55
Without using a global mutex lock in an application, is there any safe way to ensure only one instance of an application is running on a system? I have found out that bugs and errors that occur during an applications lifetime in memory can lead to many problems within a system, especially if pared with a global mutex lock. Any suggestions would be much appreciated.
Thanks for reading.
Upvotes: 1
Views: 2272
Reputation: 406
You can use Mutex to ensure a single instance app.
Put the following code in the Main function of your WinForms
app:
static class Program
{
static Mutex mutex = new Mutex(true, "<some_guid_or_unique_name>");
[STAThread]
static void Main()
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
// do the app code
Application.Run();
// release mutex after the form is closed.
mutex.ReleaseMutex();
mutex.Dispose();
}
}
}
Upvotes: 4