我第一次尝试使用互斥锁,以下代码在程序的两个独立实例上执行
public void asynchronousCode()
{
using (var mutex = new Mutex(false, "mySpecialMutex"))
{
if (!mutex.WaitOne(1000, false))
{
Console.WriteLine("First check - some one locked the mutex");
}
if (!mutex.WaitOne(3000, false))
{
Console.WriteLine("Second check- some one locked the mutex");
}
else
{
Console.WriteLine("I got the mutex");
Console.WriteLine("sleeping");
Thread.Sleep(3000);
Console.WriteLine("Awaking and Releasing mutex");
mutex.ReleaseMutex();
}
}
}
当我运行这段代码时,其中一个实例(我首先运行的那个)会打印出:
I got the mutex
sleeping
awaking and releasing mutex
另一个实例打印First check - some one locked the mutex
当第一个程序实例释放互斥锁时,它在第二个等待语句处崩溃并抛出异常。
The wait completed due to an abandoned mutex.
有什么想法可以解决我遇到的异常问题,以及如何防止它发生?
解决方案:我可能应该更仔细地阅读MSDN文档。感谢安德鲁指引我找对了方向。
您可以使用WaitHandle.WaitOne方法请求对互斥体的所有权。拥有互斥体的线程可以在多次调用WaitOne时请求相同的互斥体而不会阻止其执行。但是,线程必须调用ReleaseMutex方法相同次数才能释放对互斥体的所有权。Mutex类强制线程标识,因此只有获取互斥体的线程才能释放它。