Tuesday, November 4, 2008

Checking for Multiple Instances of a Windows Forms or Console Application

When running a windows application or console/batch application you may run into issues if you have multiple instances running on the same machine. The applications may cause contention when reading and writing to a file system or database. Depending on how you design your application, it may cause data loss.

To handle this, you can use the System.Diagnostics namespace to check for existing instances of the application. If an instance exists with a different process ID, kill the existing process.

Note: You can kill the existing instance instead using process.Kill();

// Grab the current process so you can pull it's name
Process currentProcess = Process.GetCurrentProcess();
// Get existing processes on the current machine with the same name
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process process in processes)
{
// Loop through and check for any instance with the same name
if (process.Id != currentProcess.Id)
{
MessageBox.Show("Application is already running");
Application.Exit();
return;
}
}

// This piece of code isn't necessarily required. When using Visual Studio, your windows
// app runs under [ApplicationNam].vshost. This checks for these processes as well.
processes = Process.GetProcessesByName(currentProcess.ProcessName.Replace(".vshost", ""));
foreach (Process process in processes)
{
if (process.Id != currentProcess.Id)
{
MessageBox.Show("Application is already running");
Application.Exit();
return;
}
}

No comments: