使用命名的互斥锁 [英] Using Named Mutex

查看:160
本文介绍了使用命名的互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个运行相同Windows服务的实例.他们互相检查健康状况,并报告是否发现任何问题.我有一项关键的工作需要执行,因此我正在使用故障转移方法运行它,它在Master中运行,如果Master没有响应,则它在Slave中运行.这项工作需要通过特定的串行端口进行通信,我正在尝试使用Mutex检查竞争状况.我无权访问生产环境,因此在部署之前,我想确保我的方法是正确的.因此,请建议在给定的情况下我是否可以使用Mutex.

I have two instances running of same Windows Service. They check the health of each other and report if any issue is found. I have a critical job that needs to be performed so I am running it with a fail-over approach, it runs in Master, and if Master is not responding it runs in slave. This job needs to communicate over a specific serial port, I am trying to use Mutex to check for race condition. I dont have access to production, so before deploying I want to make sure my approach is fine. So please suggest if my use of Mutex is fine for the given case.

if (iAmRunningInSlave)
{
   HealthClient hc = new HealthClient();
   if (!hc.CheckHealthOfMaster())
      return this.runJobWrapper(withMutex, iAmRunningInSlave);
   else
      return true; //master is ok, we dont need to run the job in slave
}
return this.runJobWrapper(withMutex, iAmRunningInSlave);

然后在runJobWrapper中

And then in runJobWrapper

bool runJobWrapper(bool withMutex, bool iAmRunningInSlave)
{
   if (!withMutex)
      return this.runJob(iAmRunningInSlave); //the job might be interested to know 
   Mutex mutex = null;
   string mutexName = this.jobCategory + "-" + this.jobTitle; //this will be unique for given job
   try
   {
      mutex = Mutex.OpenExisting(mutexName);
      return false; //mutex is with peer, return false which will re-trigger slave
   }
   catch
   {
      try
      { //mean time mutex might have created, so wrapping in try/catch
         mutex = new Mutex(true /*initiallyOwned*/, mutexName);
         return this.runJob(iAmRunningInSlave); //the job might be interested to know where I am running
      }
      finally
      {
         if (null!=mutex) mutex.ReleaseMutex();
      }
      return false;
   }
}

推荐答案

我最近有一个类似的问题.

I had a similar issue recently.

Mutex类的设计与.NET中的普通类有点奇怪/不同.

The design of the Mutex class is a bit weird/different from the normal classes in .NET.

使用OpenMutex检查现有的Mutex并不是很好,因为您必须捕获异常.

Using OpenMutex to check for an existing Mutex is not really nice as you have to catch an exception.

更好的方法是使用

Mutex(bool initiallyOwned, string name, out bool createdNew) 

构造函数,并检查createdNew返回的值.

constructor, and check the value returned by createdNew.

这篇关于使用命名的互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆