Single Instance Application OS wide with mutex

Done like described:

What is the correct way to create a single-instance application?

or

http://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/

The mutex works fine inside the user session. But it doesn't work, when I am switching users. May it be because one user is a domain user and the other user where I start the program is a local user? I haven't tested it yet with two local users...

I need to have only one instance on the computer.

I expect, the mutex to be OS wide. Is that a false assumption?

public partial class App : Application
{
    private static Mutex _InstanceMutex = null;

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        bool isNewMutex;
        _InstanceMutex = new Mutex(true, "{ED75DE2B-69F7-4973-A58C-3A9D49B3E48D}", out isNewMutex);
        if (!isNewMutex)
        {
            _InstanceMutex = null;
            MessageBox.Show("Only one instance allowed", "ThisApp");
            Process.GetCurrentProcess().Kill();
            Application.Current.Shutdown();
            return;
        }
        //base.OnStartup(e);
    }

    private void Application_Exit(object sender, ExitEventArgs e)
    {
        if (_InstanceMutex != null)
            _InstanceMutex.ReleaseMutex();
        //base.OnExit(e);
    }

I think you're going to want to pass MutexSecurity to the Mutex when you create it. The example at the bottom of the documentation shows how to lock a mutex down to a specific user. Also read in Remarks, that there is such thing as Global and Local sessions, which may or may not apply to you.

Mutex Constructor (Boolean, String, Boolean, MutexSecurity) to be used.

Edit

You could also try this approach:

if(!(Mutex.TryOpenExisting("Global{ED75DE2B-69F7-4973-A58C-3A9D49B3E48D}", out tempMutex)))
{
   _InstanceMutex = new Mutex(true, "Global{ED75DE2B-69F7-4973-A58C-3A9D49B3E48D}");
   //Continue startup normally
}
else
{
   //Already exists, shutdown app
}

This shouldn't throw an exception unless you set the mutex security.

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

上一篇: 每个网络一个Java应用程序实例

下一篇: 带有互斥体的单实例应用程序