我正在尝试实现不同进程之间的同步。应同步多个进程调用ProcessLock
。我能够实现它。但问题是其他线程无法进入关键部分。锁始终由同一应用程序获取。如何在不同的应用程序之间共享锁定。
public class ProcessLock : IDisposable
{
// the name of the global mutex;
private const string MutexName = "FAA9569-7DFE-4D6D-874D-19123FB16CBC-8739827-[SystemSpecicString]";
private Mutex _globalMutex;
private bool _owned = false;
// Synchronized constructor using mutex
public ProcessLock(TimeSpan timeToWait)
{
try
{
_globalMutex = new Mutex(true, MutexName, out _owned);
if (_owned == false)
{
// did not get the mutex, wait for it.
_owned = _globalMutex.WaitOne(timeToWait);
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
throw;
}
}
public void Dispose()
{
if (_owned)
{
//Releasing the lock to be acquired by different processes.
_globalMutex.ReleaseMutex();
}
_globalMutex = null;
}
}
如果三个方法正在调用此构造函数,则所有方法都应按顺序调用或以某种循环方式调用。
我有以下包装类
public class CrossProcessLockFactory
{
private static int DefaultTimoutInMinutes = 2;
public static IDisposable CreateCrossProcessLock()
{
return new ProcessLock(TimeSpan.FromMinutes(DefaultTimoutInMinutes));
}
public static IDisposable CreateCrossProcessLock(TimeSpan timespan)
{
return new ProcessLock(timespan);
}
}
在主要方法中。
using (CrossProcessLockFactory.CreateCrossProcessLock())
{
// if we get out it is ready
Console.WriteLine("Using the mutex on process 1. Press any key to release the mutex");
Console.ReadLine();
}