我使用以下代码来同步多个正在运行的进程之间对共享资源的互斥访问.
互斥锁是这样创建的:
Mutex mtx = new Mutex(false, "MyNamedMutexName");
Run Code Online (Sandbox Code Playgroud)
然后我用这个方法进入互斥部分:
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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码留给它:
public bool leaveMutuallyExclusiveSection()
{
//RETURN: = 'true' if no error
bool bRes = true;
try
{
mtx.ReleaseMutex();
}
catch
{
//Failed …Run Code Online (Sandbox Code Playgroud) 我试图第一次使用互斥锁,并在程序的两个单独的实例上执行以下代码
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,其中一个实例(我先运行的那个)打印出来
I got the mutex
sleeping
awaking and releasing mutex
Run Code Online (Sandbox Code Playgroud)
另一个实例打印
First check - some one locked the mutex
Run Code Online (Sandbox Code Playgroud)
一旦第一个实例租用互斥锁,它就会在第二个等待语句崩溃时出现异常
The wait completed due to an …Run Code Online (Sandbox Code Playgroud) c# multithreading mutex multiprocessing abandonedmutexexception