c# - 如何限制用户打开多个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();
}
解决方案
每个构建的互斥锁名称必须是唯一的。因为每个版本都有不同的程序集名称,所以可以在互斥体名称中包含此名称,如下所示。
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();
}
推荐阅读
- python - GPU 上的 Google colab 教程:“OSError:libcudart.so.10.2:无法打开共享对象文件:没有这样的文件或目录”
- swift - UIKit中的标签栏控制器问题
- arrays - (wx)Maxima:作业
- javascript - 由 div 固定标题组成的表格,但在 x 轴上没有与表格一起滚动
- reactjs - TypeError:无法读取未定义的属性(读取“img”)反应
- mysql - 跨 100 个不同表的 MySQL 查询。模式匹配表名称
- arrays - 是否有散列函数将元素对映射到数组中的索引?
- powershell - RavenDB 安装问题 System.Net.Sockets.SocketException (10013)
- c# - 添加局部视图以按计划查看
- python - 尝试在 Linux 上下载 Python 包时出错