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



TODO:

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.

 

SOLUTION:

//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");
                Thread.Sleep(5000);
                return -1;
            }
}

 

NOTES:



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading