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

I was wondering which of the following options was suggested when using Mutex (or Semaphores or ReadWriteLockSlims, etc.).

If the initial lock occurs inside or outside the try statement? It does not matter?

_mutex.WaitOne()
try
{
 // critical code
}
finally
{
  _mutex.ReleaseMutex();
}

or

try
{
  _mutex.WaitOne()
 // critical code
}
finally
{
  _mutex.ReleaseMutex();
}
+3
source share
3 answers

Perhaps this is another matter. Take a look at these posts from Eric:

In short: Imagine that there is an exception between the operator mutex.WaitOne()and try. You will leave this piece of code without a call _mutex.ReleaseMutex().

So, grab your second piece of code to make sure everything works as expected.

0
source

, , - , WaitOne, 1 , WaitOne 2. , . - , ThreadAbortException, . , , .

EDIT: , , , , , .

+2

.

. # - Mutex

:

private static object _syncLock = new object();

public void RunCriticalCode()
{
    lock (_syncLock)
    {
        // critical code
    }
}
0
source

Source: https://habr.com/ru/post/1743484/


All Articles