Usando o Mutex nomeado
Tenho duas instâncias executando o mesmo serviço do Windows. Eles verificam a saúde um do outro e relatam se há algum problema. Eu tenho um trabalho crítico que precisa ser executado, por isso estou executando-o com uma abordagem de failover, ele é executado no Master e, se o Master não está respondendo, ele é executado no slave. Este trabalho precisa se comunicar por uma porta serial específica. Estou tentando usar o Mutex para verificar a condição da corrida. Como não tenho acesso à produção, antes de implantar, quero garantir que minha abordagem esteja correta. Então, sugira se meu uso do Mutex é bom para o caso em questã
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);
E depois em 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;
}
}