Wednesday, February 4, 2009

Preventing multiple instance of an application

Hi,

.Net framework's System.Threading namespace provides Mutex class which is a synchronization primitive that can also be used for interprocess synchronization. Using this mutex object we can also control running of multiple instances of a same application. Here is the sample code to do that. The code should be wriiten on the starting point of the application obviously for a windows or console application it would be the Main() function.

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

[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");
}
}
}
}


Note: Replace the application name with your corresponding application name. Include the namespace System.Threading.

Happy coding...