C# Mutex for running single instance of a program

Here is some sample code that can be used in a c# application to make sure that only one instance of the program can run at a time. In order to do this you will use a Mutex (Mutual Exclusion) which is a type of system wide lock. In laymens terms a Mutex is like a claim to ownership of a idea. You’re telling the world that no one else can have that idea as long as you are holding claim to it. As so as you don’t need it you can let go of the ownership and then someone else can claim ownership.

class OneAtATimePlease {
	// Use a name unique to the application (eg include your company URL)
	static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");
	
	static void Main() {
		// Wait 5 seconds if contended - in case another instance
		// of the program is in the process of shutting down.
		if (!mutex.WaitOne (TimeSpan.FromSeconds (5), false)) {
			Console.WriteLine ("Another instance of the app is running. Bye!");
			return;
		}
		try {
			Console.WriteLine ("Running - press Enter to exit");
			Console.ReadLine();
		}
		finally { 
			mutex.ReleaseMutex(); 
		}
	}
}

A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.

As you can see it’s pretty simple code. You create a Mutex object. However, until you call the WaitOne function you do not actually make your claim to ownership of the mutex. So remember to do that!

Disclaimer: This code and content are taken from multithreading in C# by Joseph Albahari. I do not claim any ownership or rights to this content. I am merely copying for my own future reference and to share the knowledge.

Avatar
Alan P. Barber
Software Developer, Computer Scientist, Scrum Master, & Crohn’s Disease Fighter

I specialize in Software Development with a focus on Architecture and Design.

comments powered by Disqus
Next
Previous

Related