How to determine if a previous instance of my application is running?

后端 未结 10 1508
梦谈多话
梦谈多话 2020-12-05 10:31

I have a console application in C# in which I run various arcane automation tasks. I am well aware that this should really be a Windows Service since it nee

10条回答
  •  一向
    一向 (楼主)
    2020-12-05 10:44

    Using a kernal object is the only correct way to implement single instance protection in Windows.

    This statement:

    mutex = Mutex.OpenExisting("SINGLEINSTANCE");

    won't work if someone else copies this line from Stackoverflow and runs their program before your program, since that other guy grabbed "SINGLEINSTANCE" before you did. You want to include a GUID in your mutex name:

    mutex = Mutex.OpenExisting("MyApp{AD52DAF0-C3CF-4cc7-9EDD-03812F82557E}");

    This technique will prevent the current user from running more than one instance of your program, but will not prevent another user from doing so.

    To ensure that only one instance of your application can run on the local computer, you need to do this:

    mutex = Mutex.OpenExisting("Global\MyApp{AD52DAF0-C3CF-4cc7-9EDD-03812F82557E}");

    See the help for the CreateMutex api.

提交回复
热议问题