避免在同一机器上同时运行同一应用程序的多个实例

  • 通常,使用有名互斥体(named mutex).但是该方案有以下的缺陷
    • 互斥体的名称有被其他应用程序使用的较小,潜在风险.此时,该方案不再有效,并且很难检测到bug.
    • 该方案无法实现允许一个应用程序产生N个实例这样的一般问题.
  • 使用Process类.
 1         /// <summary>
 2         /// check whether other instance of the application is running.
 3         /// </summary>
 4         /// <returns></returns>
 5         private bool TestIfAlreadyRunning()
 6         {
 7             Process currentProcess = Process.GetCurrentProcess();
 8 
 9             foreach (var process in Process.GetProcesses())
10             {
11                 // avoid check this process itself.
12                 if(currentProcess.Id != process.Id)
13                 {
14                     //if other instance is running,the Process Name must identical.
15                     if (currentProcess.ProcessName == process.ProcessName)
16                         return true;
17                 }
18             }
19 
20             return false;
21         }
TestIfAlreadyRunning
  • Process.GetProcesses()也可以传递机器名称.这样返回的就是远程机器上运行的所有进程.

转载于:https://www.cnblogs.com/robyn/p/3812515.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值