Kornelije Petak
Kornelije Petak

Reputation: 9572

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:

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?

Upvotes: 3

Views: 4417

Answers (2)

Anders Forsgren
Anders Forsgren

Reputation: 11111

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

Upvotes: 1

Mithir
Mithir

Reputation: 2421

One way to do this is, by another service maybe, do something like this:

Process[] processes = Process.GetProcessesByName("Program");

will give you all the active processes of your program.

then you can get the directory from this:

string fullPath = process.MainModule.FileName;

Compare the directories of all instances and if two has the same folder, close one of them.

Upvotes: 0

Related Questions