首页 > 解决方案 > 如何限制用户打开多个exe实例

问题描述

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

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

这是我尝试过的。下面的代码帮助我维护我的应用程序的单个实例,但它不区分开发人员构建和客户端构建。我希望用户能够同时打开两个构建的单个实例。

/// 应用程序的入口点

    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();
    }

标签: c#.netbuildmutexsemaphore

解决方案


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

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();
}

推荐阅读