I am trying to achieve synchronization between different processes. Multiple process calling ProcessLock
should be synchronized. I am able to achieve it. But problem here is that Other threads are unable to enter critical section. Lock is always acquired by same application. How can I share the lock between different application.
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;
}
}
If three methods are calling this constructor all should call sequentially or some round robin fashion.
I have following wrapper class
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);
}
}
And inside main method.
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();
}