为什么以下结构会导致AbandonedMutexException.即使有错误或方法返回.互斥体正在被释放.
static Mutex WriteMutex = new Mutex(false, @"Global\mutex2203");
public static void Demo()
{
try
{
WriteMutex.WaitOne();
//rest of coding stuff here
}
finally
{
WriteMutex.ReleaseMutex();
}
}
Run Code Online (Sandbox Code Playgroud)
接收报告无法重新生成错误.
编辑:WriteMutex.WaitOne();没有其他代码发生异常.只有这种方法才能触及互斥锁.
一个AbandonedMutexException当一个线程获取被抛出Mutex另一个线程已经通过不释放(参见离开废弃对象AbandonedMutexException).您在问题中引用的代码不一定是导致异常的代码,只是"接收"它(即检测抛出异常的情况).
也就是说,另一个线程中的代码(可能是相同的方法但可能不是)获取Mutex但不释放它并允许其线程退出而Mutex不会被释放.然后运行上面显示的代码的线程在尝试获取时抛出异常Mutex.
异常发生在哪里?当你这样做时,它会发生吗WriteMutex.WaitOne();?
如果是这样,则必须有某些东西(可能不在您发布的代码中)取得了它的所有权,然后在您获得异常之前退出。
由于交换线程,使用异步方法也可能成为使用互斥体的代码的问题。确保您没有以不兼容的方式使用任何这些东西。
Also, be aware that named mutexts are not local to your application: other processes could be screwing with it (and the problem could be there). If you want something local, don't give it a name, or even better use something more efficient and less error prone like the lock keyword for such cases.
Some nice details about using Mutex properly (and avoiding issues like you seem to have) are here: What is a good pattern for using a Global Mutex in C#?