Click to See Complete Forum and Search --> : [RESOLVED] Allow only one instance of the program to run ?


bluebarca
May 3rd, 2009, 12:07 PM
how can i ensure that only one instance of my program is running at anytime and don't allow second instance to run if the first instance is still running. I've read somewhere that i have to use a Mutex variable; but i don't know how to use it.

STLDude
May 3rd, 2009, 01:02 PM
Maybe this (http://blogs.msdn.com/pedrosilva/archive/2005/03/09/391381.aspx).

toraj58
May 4th, 2009, 01:59 AM
yes, one way is Mutex because it is cross process accesible Object.
another way is looking at list of running processes using ProcessInfo.

foamy
May 4th, 2009, 03:19 AM
I'd go with toraj's suggestion, something like this:


using System;
using System.Diagnostics;

namespace MyApplication
{
class Program
{
static void Main()
{
Process[] procs = Process.GetProcessesByName("MyApplication");
if (procs.Length > 1)
return;
else
Console.WriteLine("Hello World!");
}
}
}

bluebarca
May 4th, 2009, 10:39 AM
i've tried foamy's way of getting the number of processes by name and seeing if its larger than 1 then close the new process and it worked. But i have sort of a small question; when i run the application from visual studio the process name is "processName.vshost.exe" but when i run it from the its exe file its name is normal i.e. "processName.exe"





anyway thank you all for the help;
Best Regards;
bluebarca