How To Ensure One Instance Of A C# Console Application Is Running


Have you ever wanted to only allow one instance of an EXE to be running.  For instance you have an EXE name c:\temp\myexe.exe, and you want to not allow it to have more than 1 running instance.



//declare class level variable here
private static readonly Mutex mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetName().CodeBase); 

//now check in the main() method if we are running and error if we are
static int Main(string[] args)
            //make sure we only have one....
            if (!mutex.WaitOne(TimeSpan.Zero, true))
                Console.WriteLine("Another instance already running");
                return -1;