I was wondering which of the following was the suggested pattern when using Mutex (or Semaphores or ReadWriteLockSlims etc.).
Should the initial lock happen inside or outside of the try statement? Is it unimportant?
_mutex.WaitOne()
try
{
// critical code
}
finally
{
_mutex.ReleaseMutex();
}
or
try
{
_mutex.WaitOne()
// critical code
}
finally
{
_mutex.ReleaseMutex();
}
Maybe it is a different. Take a look into these posts from Eric:
In short:
Just imagine there happens an exception between the
mutex.WaitOne()and thetrystatement. You’ll leave this chunk of code without calling the_mutex.ReleaseMutex().So take your second piece of code to be sure everything works as expected.