I have a console application in C# and I want to restrict my application to run only one instance at a time. How do I achieve this in C#?
-
Duplicate http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application – KindDragon Dec 11 '10 at 04:39
6 Answers
I would use a Mutex
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
}
}

- 4,404
- 3
- 42
- 58

- 48,814
- 22
- 151
- 184
-
1
-
Thanks. I am using this in a WinForms project in VS2015. I merged the above with the Main() in program.cs , so that the "// Do stuff" location would have these 3 VS-generated lines: " Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); " Also added " using System.Threading; " at the top of program.cs . – Doochz Jan 22 '16 at 02:24
If you decide to use a Mutex for that purpose, there are some pitfalls you should be aware of:
If you want to limit the application to one instance per machine (i.e. not one per logged on user), then you will need your mutex name to start with the prefix
Global\
. If you don't add this prefix, a different instance of the mutex will be created by the OS for each user.If you are running on a Windows Vista or later machine with UAC enabled, and by some chance the current application instance is running as an admin, then the next instances will fail detecting it, and you will get permission exceptions. To avoid this you need to specify a different set of permissions for the Mutex when creating it.

- 583
- 7
- 13

- 5,989
- 1
- 24
- 26
-
6Good pitfalls. Another is that if you are running two programs that hate each other, one of them could try to mount a denial-of-service attack against the user by taking out the named mutex of the other program and never releasing it. – Eric Lippert Dec 06 '10 at 23:26
-
3Nice... But I doubt this is worth protecting from, since an "evil" program, once you trust it enought to run it, can mess up other programs anyway and doesn't need the mutex for that. For example it can kill other processes, corrupt the other program's installed files, change its shortcuts, or uninstall it altogether... – Ran Dec 07 '10 at 05:50
-
@Ran: Sure, this is in some ways one of Raymond Chen's "you're already behind the airtight hatchway" issues. However, the level of permissions required to take out a mutex might be different than the level of permission necessary to do those other things, which all ought to require full trust. I don't know whether partially trusted programs are allowed to take out named mutexes or not; it would be interesting to find out. – Eric Lippert Dec 08 '10 at 16:55
-
@Eric Lippert: running in the context of the user without any special permissions, you can read the user's mutex, but also change shortcuts, kill the user's processes, close windows or manipulate them to make them disfunctional, delete files from data folders, etc. You *do* need admin privileges in order to uninstall apps or delete from "Program Files". But even that's really easy because when the evil program's Setup was typically running as admin and could have done *absolutely anything* it wanted to on the machine. Such as install a service running as SYSTEM for future malicious use... – Ran Dec 08 '10 at 18:41
-
@Ran: Right; I'm not thinking so much about the permissions granted by the operating system to the user. I'm thinking about the CAS permissions granted by the .NET security policy to the assembly/appdomain. Remember, the evil program might not be installed at all. It might be a silverlight app running from a web site, it might be a VSTO addin being pulled from an intranet site, and so on. The JScript code on a web page also runs in the security context of the user, but we don't let it delete files. Same thing here; the C# code might have its permissions restricted. – Eric Lippert Dec 08 '10 at 18:45
-
@Eric Lippert: Well in that case I think we would be safe because code running under IE would be running in low integrity and will not be able to access the Mutex which by default has a high integrity ACL. (I actually had to work around this once, when I wanted to access my application's Mutex from a BHO...) – Ran Dec 08 '10 at 18:50
-
Anyway, let's agree that you should always analyze the risk to understand from what you should protect, and add defenses as needed... – Ran Dec 08 '10 at 19:00
-
Could you elaborate on how to specify a different set of permissions or what they should be? I'm guessing the way to go is to use `SetAccessControl` on the mutex object, but what exactly to pass there to circumvent the problem is beyond me. – takrl Mar 15 '12 at 16:39
-
@takrl: the constructor of the `Mutex` object has an overload which accepts a security object. You should use this constructor instead of creating the `Mutex` and then calling `SetAccessControl`, to avoid a race condition (where the other instance of the app might try to access the mutex after it was created but before permissions were changed). The securty object represents the ACL you will give the object. I would need to understand the requirements of your application in order to figure out what the appropariate permissions would be. Maybe you can ask that in a separate question.. – Ran Mar 15 '12 at 17:56
-
Thanks, I'll probably do that, I just need to do some more experimenting on the three OS's I need to support to come up with a proper minimal example. – takrl Mar 16 '12 at 07:34
There are many ways, such as -
- Enumerating list of processes before starting and denying the startup if process name already exists.
- Creating a mutex on startup and checking if mutex already exists.
- Launching a program through a singleton class.
Each is demoed below:
http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx
http://www.codeproject.com/KB/cs/restricting_instances.aspx
http://www.codeproject.com/KB/cs/singleinstance.aspx
Each has its pros and cons. But I believe the creating mutex is the best one to go for.

- 56,430
- 9
- 115
- 140

- 22,211
- 14
- 71
- 124
Adding this answer because previous ones did not work on linux(ubuntu 14.0.4 tested) with .net core1.1 and because this question is high up in search results. Variation of @MusuNaji's solution, if it wasn't already obvious to you.
private static bool AlreadyRunning()
{
Process[] processes = Process.GetProcesses();
Process currentProc = Process.GetCurrentProcess();
logger.LogDebug("Current proccess: {0}", currentProc.ProcessName);
foreach (Process process in processes)
{
if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id)
{
logger.LogInformation("Another instance of this process is already running: {pid}", process.Id);
return true;
}
}
return false;
}
This answer is also posted on my dotnet core specific question here: Single instance dotnetcore cli app on linux

- 6,157
- 10
- 35
- 68
here is a solution that worked for me
private static bool AlreadyRunning()
{
Process[] processes = Process.GetProcesses();
Process currentProc = Process.GetCurrentProcess();
foreach (Process process in processes)
{
try
{
if (process.Modules[0].FileName == System.Reflection.Assembly.GetExecutingAssembly().Location
&& currentProc.Id != process.Id)
return true;
}
catch (Exception)
{
}
}
return false;
}
I then check the output of this method at program startup.

- 1,584
- 21
- 26
-
On .net core(linux at least) it seems worth it to check if process.Modules.Count >0. Better to prevent exceptions then to let them happen and ignore right? – BillHaggerty Jun 23 '17 at 12:31
The most straight-forward answer for me, shown below, taken from Madhur Ahuja posted link (http://www.webskaper.no/wst/creatingasingleinstanceapplicationinc-aspx/) - reproduced here (the code project solutions were hidden from me).
The important point was to hold the mutex until the process is complete (obvious I guess).
bool createdNew;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
{
if (createdNew) {
// process
}
else {
// in my case, quietly exit
}
}

- 107
- 7