我使用以下代码在多个正在运行的进程之间同步对共享资源的互斥访问。
互斥锁是这样创建的:
Mutex mtx = new Mutex(false, "MyNamedMutexName");
然后我用这个方法进入互斥部分:
public bool enterMutuallyExclusiveSection()
{
//RETURN: 'true' if entered OK,
// can continue with mutually exclusive section
bool bRes;
try
{
bRes = mtx.WaitOne();
}
catch (AbandonedMutexException)
{
//Abandoned mutex, how to handle it?
//bRes = ?
}
catch
{
//Some other error
bRes = false;
}
return bRes;
}
这个代码离开它:
public bool leaveMutuallyExclusiveSection()
{
//RETURN: = 'true' if no error
bool bRes = true;
try
{
mtx.ReleaseMutex();
}
catch
{
//Failed
bRes = false;
}
return bRes;
}
但是发生的情况是,如果正在运行的进程之一崩溃,或者如果它从任务管理器中终止,互斥锁可能会返回AbandonedMutexException
异常。所以我的问题是,摆脱它的优雅方式是什么?
这似乎工作正常:
catch (AbandonedMutexException)
{
//Abandoned mutex
mtx.ReleaseMutex();
bRes = mtx.WaitOne();
}
但是在这种情况下我可以进入互斥部分吗?
有人可以澄清吗?