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
{
///<summary>
/// The main entry point for the application.
///</summary>
[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…

yenkay

Advertisements

One thought on “Preventing multiple instance of an Application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s