如何限制用户打开多个exe实例

How to restrict user from opening more than one instance of the exe

我的应用程序在两个构建版本中作为 exe 发布 - DeveloperBuild 和 ClientBuild(UAT)。 DeveloperBuild 用于内部开发人员和 QA 测试,而 ClientBuild 用于最终客户。 'DeveloperBuild' 和 'ClientBuild' 实际上是程序集名称。

我想限制用户打开多个 build.In 简单的话,用户应该能够打开 DeveloperBuild 的单个实例 和 ClientBuild 的单个实例同时进行, 但不应允许用户同时打开多个 DeveloperBuild 或 ClientBuild 实例。

这是我试过的。下面的代码帮助我维护我的应用程序的单个实例, 但不区分Developer Build和Client Build。我希望用户有优势同时打开两个构建中的每一个的单个实例。

/// 应用程序的入口点

    protected override void OnStartup(StartupEventArgs e)
    {           
        const string sMutexUniqueName = "MutexForMyApp";

        bool createdNew;

        _mutex = new Mutex(true, sMutexUniqueName, out createdNew);

        // App is already running! Exiting the application  
        if (!createdNew)
        {               
            MessageBox.Show("App is already running, so cannot run another instance !","MyApp",MessageBoxButton.OK,MessageBoxImage.Exclamation);
            Application.Current.Shutdown();
        }

        base.OnStartup(e);

        //Initialize the bootstrapper and run
        var bootstrapper = new Bootstrapper();
        bootstrapper.Run();
    }

每个构建的互斥体名称必须是唯一的。因为每个版本都有不同的程序集名称,所以您可以将此名称包含在互斥体的名称中,如下所示。

protected override void OnStartup(StartupEventArgs e)
{           
    string sMutexUniqueName = "MutexForMyApp" + Assembly.GetExecutingAssembly().GetName().Name;

    bool createdNew;

    _mutex = new Mutex(true, sMutexUniqueName, out createdNew);

    // App is already running! Exiting the application  
    if (!createdNew)
    {               
        MessageBox.Show("App is already running, so cannot run another instance !","MyApp",MessageBoxButton.OK,MessageBoxImage.Exclamation);
        Application.Current.Shutdown();
    }

    base.OnStartup(e);

    //Initialize the bootstrapper and run
    var bootstrapper = new Bootstrapper();
    bootstrapper.Run();
}