Example of how to make sure only one instance of your program is running.
I needed a way to ensure that only one instance of my program was running at any given time. So after a little googling this is what I came up with:
Here is some sample code that can be used to ensure that only one instance of a program is running.public static void Main(string[] args) { // bool used to determine if we created a new mutex bool createdNew; // give a unique name for the mutex,
// prefix it with Local\ to ensure that it's created in the per-session namespace, not the global namespace.
string mutexName = @"Local\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; // Create a new mutex object with given name Mutex m = new Mutex(false, mutexName, out createdNew); // If the mutex already exists then don't start program becase // another instance is already running. if(!createdNew) return; // // Do work like Application.Run(new MainForm()); // // Release the mutex resources m.ReleaseMutex(); }
This little trick seems to work for my needs.
Update: Added "Local\" to the mutex name per Shawn's suggestion