Friday, August 7, 2009

Create Single Instance Application using Mutex

Mutex is a windows kernel level object typically used for thread synchronization across AppDomain and Process boundaries. We can easily use Mutex to confirm that only one instance of our application will run at a time. Following code snippet shows the way of achieving the goal:
using System;
using System.Windows.Forms;
using System.Threading;

namespace SingleInstanceApp
{
static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Mutex objMutex = null;
const string MutexName = "THEONE";
try
{
//Open Mutex if already exists
objMutex = Mutex.OpenExisting(MutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
//Cannot be opened because no Mutex exists
}
if (objMutex == null)
{
//Create a new instance of Mutex
objMutex = new Mutex(true, MutexName);
}
else
{
//Close Mutex because one instance already exists
objMutex.Close();
return;
}
Application.Run(new MainForm());
}
}
}

No comments:

Post a Comment