Home > .Net CLR > Use mutex to guaranty uniqueness

Use mutex to guaranty uniqueness

Mutex can be used to make sure the application run only as one instance. Traditionally I used to get the running process names and search to see if my app running or not. That approach can be replaced by using Mutex which is simpler and easier to use (at least to me).

Following code are from a WPF application:

 

public partial class Window1 : Window
  {
    private Mutex myMutex = null;
    private const string MutexName = “RUNMEONLYONCE”;

    public Window1()
    {
      InitializeComponent();
      try // Try and open the Mutex
      {
        myMutex = Mutex.OpenExisting(MutexName);
      }
      catch (WaitHandleCannotBeOpenedException)
      {
        // Cannot open the mutex because it doesn’t exist
      }

      // Create it if it doesn’t exist
      if (myMutex == null)
      {
        myMutex = new Mutex(true, MutexName);
      }
      else
      {
        // Close the mutex and exit the application
        // because we can only have one instance
        myMutex.Close();
        MessageBox.Show(“An instance already running.”);
        Environment.Exit(0); 
      }
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      myMutex.Close();
    }

If the Mutex exist in a running instance of the application, Mutex.OpenExisting(MutexName) will return it.

Mutex is mainly design for managing Asynchronous task across process, but in this case we simply use it as a flag. 

Advertisements
Categories: .Net CLR
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: