Run a Single Instance of An Application (.NET)

Sharing is Caring

Occasionally, as a software developer you want to restrict a user to only allow them to run one instance of an application on their machine. The reasons why vary dramatically, but often it is because it could make large system changes, maybe their is some business reason, or perhaps it just doesn’t make sense.

Restricting an application to only run one instance is actually really simple in .NET although it does require a little bit of thinking and explanation. Most software developers with a university education would have read “Operating System Concepts” and spent significant time hearing about mutexes and other different solutions provided by the operating system or virtual environment.

The simplest and best method of only allowing one application to be used is to use a mutex in program.cs in the Main method. We will not search the process table as this really only works if the user doesn’t make a copy of the application and change the name.

What is a mutex? Mutex is short for mutual exclusion. A mutex is a protected variable that provides a method of controlling access also known simply as a lock. If you have done any serious multi-threading you have probably used the lock object, or a mutex to control access to critical sections of code. The MSDN includes a great description of the mutex class and should be referenced.

The real elegance of using a mutex is that the operating system will keep track of it, and ensure that another process can’t be started as long as the mutex runs. Of course, using a mutex also is the cleanest and simplest code. 🙂

We begin adding the code by opening program.cs and then by creating the mutex in static class Program. We need to ensure we pass in something relatively unique as the string in Threading.Mutex, often I use the name of the application or the GUID what you use is really up to you.

static class Program
{
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
[STAThread]
static void Main()
.....

The real advantage of having the named mutex is that we’re able to use it literally anywhere on the machine to check and see if the process is running. We will be using one of the overloaded constructors to ensure we don’t wait for the mutex. We do this because we’re not synchronizing threads, and in most cases it wouldn’t really make sense to wait for one application to close so we can start another. We pass in true because we don’t want to try and acquire the lock if it already exists.

Our program.cs looks like the following so far.

static class Program
{
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
[STAThread]
static void Main()
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
...

We now need to add the contents to our if block and then eventually decide on what to do if an instance is already running. I typically just notify the user through a messagebox or console window depending on what the application is for.


static class Program
{
static System.Threading.Mutex mutex = new System.Threading.Mutex(true, "9245fe4a-d402-451c-b9ed-9c1a04247482");
[STAThread]
static void Main()
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
//Ensure we release mutex
// In .NET 2.0 AbandonedMutexException is thrown in next thread that acquires mutex
mutex.ReleaseMutex();
}
else
{
//Maybe log this to file
MessageBox.Show(Application.ProductName + " is only allowed one instance.");
}
}
}

It could also be possible to use the Windows API and focus the other application. Generally, if you’re working on a normal windows application just notifying the user is acceptable. I generally try my best to avoid the Windows API in .NET.

We need to ensure we release the mutex. “If a thread terminates without releasing a Mutex, the mutex is said to be abandoned. This is a serious programming error because the resource the mutex is protecting might be left in an inconsistent state.” MSDN

Keep in mind that in at least .NET 3.5, if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.

Comments are closed.