How to implement single instance per machine application?

I have to restrict my .net 4 WPF application so that it can be run only once per machine. Note that I said per machine, not per session.
I implemented single instance applications using a simple mutex until now, but unfortunately such a mutex is per session.

Is there a way to create a machine wide mutex or is there any other solution to implement a single instance per machine application?


I would do this with a global Mutex object that must be kept for the life of your application.

MutexSecurity oMutexSecurity;

//Set the security object
oMutexSecurity = new MutexSecurity();
oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow));

//Create the global mutex and set its security
moGlobalMutex = new Mutex(True, "Global{5076d41c-a40a-4f4d-9eed-bf274a5bedcb}", bFirstInstance);
moGlobalMutex.SetAccessControl(oMutexSecurity);

Where bFirstInstance returns if this is the first instance of your application running globally. If you omited the Global part of the mutex or replaced it with Local then the mutex would only be per session (this is proberbly how your current code is working).

I believe that I got this technique first from Jon Skeet.

The MSDN topic on the Mutex object explains about the two scopes for a Mutex object and highlights why this is important when using terminal services (see second to last note).


I think what you need to do is use a system sempahore to track the instances of your application.

If you create a Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name.

Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes.

EDIT: Note that I am not aware if this approach works across multiple windows sessions on a machine. I think it should as its an OS level construct but I cant say for sure as i havent tested it that way.

EDIT 2: I did not know this but after reading Stevo2000's answer, i did some looking up as well and I think that the "Global" prefixing to make the the object applicable to the global namespace would apply to semaphores as well and semaphore, if created this way, should work.


您可以在%PROGRAMDATA%的某处打开一个具有独占权限的文件。第二个启动的实例将尝试打开相同的文件,如果它已经打开,则会失败。

链接地址: http://www.djcxy.com/p/9054.html

上一篇: “**”在Python中意味着什么?

下一篇: 如何实现每台机器应用程序的单个实例?