How to make sure only one instance is running

Some application cannot be run in multiple instance for several reasons. So you need to avoid a second instance will run, but how?
You cannot directly block the execution of your application, so you need to take care of the problem in your code.

In fact it is realy simple. All you need is the class Mutex, delivered in the .Net Framework.
And here is how:

At first add the using of System.Threading, then use the code below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
static void Main()
{
 string mutex_id = "MY_APP";
 using (Mutex mutex = new Mutex(false, mutex_id))
 {
  if (!mutex.WaitOne(0, false))
  {
   MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
   return;
  }
  // Do stuff
 }
}

Comments

Popular posts from this blog

How to support multiple languages in WPF