I have a C# application code in which I use a mutex to synchronise some code during the creation of an object. The object constructor acquires the mutex and ONLY releases it when the object is no longer needed (during app shutdown). Thus one place to release the mutex would be in the object destructor. The problem that arose is that sometimes I got an exception during the call to ReleaseMutex() in the object destructor. The exception is: "Object synchronization method was called from an unsynchronized block of code". It appears that the thread that does gabage collection which calls the object destructor sometimes is not the same thread that waits for the mutex (Mutex.WaitOne(false, namedMutex)) in the first place. How do I syncrhonize the acquire and release of the mutex on the same thread to avert this exception? Thanks for your help!
public class MyObject
{
static ExtDeviceDriver devDrv;
private Mutex mut = new Mutex(false,myMutex);
public MyObject()
{
mut.WaitOne();
//Thread safe code here.
devDrv = new ExtDeviceDriver();
}
~MyObject()
{
mut.ReleaseMutex();
}
}