Preventing multiple process instances of a single executable

前提是你 提交于 2019-12-10 21:13:11

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10480141/preventing-multiple-process-instances-of-a-single-executable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!