Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should mutex.WaitOne() inside or before the try/finally block

Tags:

c#

mutex

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();
}
like image 269
chillitom Avatar asked Oct 20 '25 03:10

chillitom


2 Answers

The only way these could be different is if an exception occurred after WaitOne but before the try start in example 1 or after the try start but before WaitOne in example 2. In the first case, the mutex won't be released and in the second case a release might be attempted even though there is no pending wait. The exception would have to be something severe like ThreadAbortException for it to occur in either place. However, if the mutex is contained in a using block, neither would be a problem.

EDIT: after reading Eric's post on this topic that Oliver linked to, I think even with a using block, the situation is not perfect and that simply going with your second version as Oliver suggests is your best option.

like image 180
Daniel Renshaw Avatar answered Oct 21 '25 17:10

Daniel Renshaw


Maybe it is a different. Take a look into these posts from Eric:

  • Subtleties of C# IL codegen
  • Locks and exceptions do not mix

In short: Just imagine there happens an exception between the mutex.WaitOne() and the try statement. 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.

like image 40
Oliver Avatar answered Oct 21 '25 18:10

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!