I have several sections of code that I need to protect with a Mutex. The problem is that the code looks something like this:
lock(mylockobject) {
if(!foo())
throw new MyException("foo failed");
if(!bar())
throw new MyException("bar failed");
}
Using lock, it works as I'd like, but now I need to use a mutex. The obvious problem here is that if I acquire the mutex and foo() or bar() fails, I would have to explicity release the mutex before throwing each exception.
In C++, I would take advantage of the scope of an object created on the stack, and would lock the mutex in the object's constructor, and then release it in the destructor. With .NET's garbage collection, I didn't think this would work. I wrote a test app and confirmed that if I do something like this:
public class AutoMutex
{
private Mutex _mutex;
public AutoMutex(Mutex mutex)
{
_mutex = mutex;
_mutex.WaitOne();
}
~AutoMutex()
{
_mutex.ReleaseMutex();
}
}
and then have code like this:
// some code here...
Mutex my_mutex = new Mutex(false, "MyMutex");
{ // scoping like I would do in C++
AutoMutex test = new AutoMutex(my_mutex);
test = null;
}
The destructor (finalizer?) doesn't get called until much later.
Google hasn't yet pointed me in the right direction, but I'm still working on it... Please let me know how you might solve this little problem, if it's even possible.