Reputation: 2529
I am a little confused on understanding how the Mutex
class works.
Say I have a code like that will be executed by multiple tasks:
bool lockAcquired = mutex.WaitOne();
try
{
sharedVar += 1;
}
finally
{
if (lockAcquired) mutex.ReleaseMutex();
}
My understanding (correct me if I am wrong) is that moment it reaches mutex.WaitOne()
, it will wait first for another thread to execute ReleaseMutex()
before going on to execute the succeeding statements. Therefore, it will not go on and execute the try..finally
statement if another thread has the lock. If it acquires the lock, then that is the time when it will proceed on executing the next codes. lockAcquired
will be true
then. My question is, why do I need to check if lockAcquired
is true
inside the finally
statement if it will only be executed when the lock is acquired. It would mean that the if
statement inside the finally
block would always be executed. Thanks.
Upvotes: 2
Views: 271
Reputation: 244757
According to the documentation, the return value is:
true
if the current instance receives a signal. If the current instance is never signaled,WaitOne
never returns.
This means there is no point in checking the returned value, it will never be false
.
Upvotes: 1
Reputation: 182753
There is no reason to check lockAcquired
in this code. And if you were going to check it, you should probably check it before clobbering the state that the mutex protects.
Upvotes: 0