Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing multiple process instances of a single executable

I am using .NET with C#.

I want to prevent two instances of the same executable to run at the same time, but I don't want to prevent the same process that is run from another folder.

For example, I have an executable that is in two different locations:

  • C:\MyProject\Master\Program.exe

  • C:\MyProject\Slave\Program.exe

These are the same .exe files, but in two different locations.

I want to allow one instance of Program.exe that is run from Master folder and one instance from the Slave folder, but no two of any.

I've tried to do this by checking the number of processes that have the same name (Process.GetProcessesByName), but then I can't differ the two.

The closest I have found is to get the Modules from the Process.

The first one in the list is ProcessModule of the exe. But I am not sure if this will always be the first one on the list. Is there any guarantee for that, or is there a better solution to the explained problem?

like image 952
Kornelije Petak Avatar asked May 19 '26 05:05

Kornelije Petak


1 Answers

I would use a global mutex instead of relying on the assembly name. Another application may be using the same file name for example.

See e.g. this answer: Run single instance of an application using Mutex

like image 145
Anders Forsgren Avatar answered May 21 '26 22:05

Anders Forsgren