Last Modified September 29, 2026
- Home
- Guides
- Advanced Topics
- Implementing MUTEX protection
Implementing MUTEX protection
MUTEX protection will allow just one instance of the Application to be running on a given computer / server.
You would typically apply this strategy for an enterprise application to protect against the following:
- the Application running on a computer accessed by multiple users using Remote Desktop to run multiple
instances of the application simultaneously
- the Application being run on a Server with multiple concurrent instances of the Application
The implementation requires a change to the main program file to create a MUTEX, detect if the Application
is already running and taking an action if an instance is already running (ex: stop the application, bring the current instance to the
forefront, ...).
In the code sample page, we have included a MUTEX variant of the HelloWord C# Win32 code sample, where we have replaced
the program.cs code as follows:
// non-MUTEX version of program.cs of HelloWorld project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HelloWorld
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new HelloWorld());
}
}
}
// MUTEX version of program.cs of HelloWorld project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace HelloWorld
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
// set up MUTEX, and run only if this is only instance of the App HelloWorld
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "HelloWorld", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new HelloWorld());
}
else
{
// code for when more than one instance is running
//
// here we just show message box message
MessageBox.Show("HelloWorld is already running.");
}
}
}
}
}