you're reading...
Programming Issues/Tips

Using the Mutex Class to Ensure Only One Instance of a Managed App Runs.

1. Introduction.

1.1 It is not uncommon to require that only one instance of a program be executable at any one time.

1.2 A common programming technique used to ensure this involves the use of a system-wide mutex object.

1.3 This blog provides a sample implementation of such a single-instance-only application and expounds on the use of the Mutex class for such a purpose.

2. The Mutex Class.

2.1 There are 3 basic properties of a mutex instance that are significant for our purpose at hand :

  • The name of the mutex.
  • Creation of the mutex.
  • Ownership of the mutex.

2.2 A mutex can be either named or unnamed. If a mutex is named, it is eligible to be a system-wide mutex that can be accessed from multiple processes. If a mutex is unnamed, it is an anonymous mutex which can only be accessed within the process in which it is created.

2.3 A mutex can only be created once. This is especially true of a named mutex. The .NET Mutex class has a constructor version that takes an out boolean parameter that can be used to indicate whether the Mutex instance was freshly created as a result of the constructor call or whether the Mutex instance is a pre-existing one.

2.4 A mutex object can be owned by a thread. When owned, it can only be owned by one single thread. When it is owned by a thread, other threads cannot own it until the original thread owner releases it. A thread which wants to own a mutex calls the Mutex instance’s WaitOne() method. An owning thread which wants to release the Mutex calls the ReleaseMutex() method.

2.5 So how does the Mutex class help us to limit the runnable number of instances of an application to just one ? The following is a summary :

  • We use a system-wide named mutex object so that it can be accessed from more than one application (including other instances of the same program).
  • The first instance of our target application will always be the first to create the named mutex.
  • A second instance of the application will attempt to create the mutex but will know that the mutex has already been created.
  • This indicates that a prior instance of the same program is currently running. The second instance will immediately terminate. 
  • Though this is not strictly required, it is good practice to let the first instance of the target application own the mutex until the end of the application. This is known as initial ownership. At the end of the application run, ReleaseMutex() is called to release ownership of the mutex.
  • I mentioned that it is not stricltly required that the first instance of the target application own the mutex because all that is required is that the second instance be notified that the named mutex has already been created.
  • Initial ownership of the mutex is a programming practice that is better maintained so as not to cause confusion. If initial ownership is acquired, then ReleaseMutex() must be called on the Mutex instance when the program ends.

3. Example Code.

3.1 Listed below is a sample skeletal code that demonstrates the concepts that we have discussed thus far :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace CSConsoleApp01
    class Program

        static void Main(string[] args)
            bool mutexWasCreated;
            // We attempt to instantiate a system-wide mutex
            // with a specific name "PROGRAM_MUTEX_NAME".
            // The first parameter is set to "true" so that
            // if the mutex is now created as a result of
            // this call this thread will be the owner of
            // the mutex.
            // The "mutexWasCreated" boolean variable is
            // used as the "out" parameter so that it
            // receives information concerning whether
            // the mutex is first created as a result
            // of the call. The following are possible
            // values :
            // 1. true - the mutex is created as a result
            // of the call.
            // 2. false - the mutex already existed prior
            // to the call.
            Mutex m = new Mutex(true,
                                out mutexWasCreated);

            if (mutexWasCreated == false)
                // The mutex already existed.
                // From this, we know that a
                // previous instance of this
                // program is currently running.
                // We exit immediately.

            // If we reach this point, it means
            // that the mutex had not existed
            // before and that it is now freshly
            // created.
            // Furthermore, this program is currently
            // the owner of the mutex.

            // ... the rest of the program runs here ...

            // At the end of the program, release
            // the mutex so that another instance
            // can create it again.

4. In Conclusion.

4.1 The Mutex class is certainly useful for exerting programmatic control over the number of running instances of an application.

4.2 I hope to do more writeups on the Mutex class in the furture. One area of research I that hope to study is the AbandonedMutexException which is thrown when a thread acquires a Mutex object that another thread has abandoned by exiting without releasing it.



About Lim Bio Liong

I've been in software development for nearly 20 years specializing in C , COM and C#. It's truly an exicting time we live in, with so much resources at our disposal to gain and share knowledge. I hope my blog will serve a small part in this global knowledge sharing network. For many years now I've been deeply involved with C development work. However since circa 2010, my current work has required me to use more and more on C# with a particular focus on COM interop. I've also written several articles for CodeProject. However, in recent years I've concentrated my time more on helping others in the MSDN forums. Please feel free to leave a comment whenever you have any constructive criticism over any of my blog posts.


One thought on “Using the Mutex Class to Ensure Only One Instance of a Managed App Runs.

  1. Thank you very much for your work 🙂 Article is really clear and very helpful to me at this point. Greetings!

    Posted by Patryk Tymko | July 26, 2013, 9:26 am

Leave a Reply

Fill in your details below or click an icon to log in:

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: