I have an app that creates an object that needs to be locked as this object creates an external hardware device object (via third party DLL) and the hardware device object can only be created once. When multiple instances of this app are launched, only the first instance should be able to create this C# object. The subsequence instances should see that the object has been locked and object can not be created. I used a mutex as this object creation occurs in multiple app instances (multiple processes). The code doesn’t lock with the mutex however. Am I running multiple instances in which each one creates its own lock?
public sealed class MyObject
{
private static MyObject _myObject;
static ExtDeviceDriver devDrv;
private readonly static Mutex mut = new Mutex();
private MyObject()
{
mut.WaitOne();
//Thread safe code here.
devDrv = new ExtDeviceDriver();
}
~MyObject()
{
mut.ReleaseMutex();
}
// object accessor
public static MyObject GetMyObject
{
get
{
if (_myObject == null)
_myObject = new MyObject();
return _myObject;
}
}
}
I guess you should use named mutex (See this article on MSDN).
So, try to use this constructor to create a named Mutex. Besides you should check, whether it already exists with Mutex.OpenExisting Method (Consider the example given in this very article; is tells how to check, create, utilize a named mutex).
EDIT
See Mutex Class:
And Mutex Constructor (Boolean, String), that says, that a bool argument must be set to: