It seems that these code snippets ought to behave identically:
if (Monitor.TryEnter(lockObject))
{
try
{
DoSomething();
}
finally
{
Monitor.Exit(lockObject);
}
}
bool lockAcquired;
try
{
Monitor.TryEnter(lockObject, ref lockAcquired);
if (lockAcquired)
{
DoSomething();
}
}
finally
{
if (lockAcquired)
{
Monitor.Exit(lockObject);
}
}
I see from the MSDN documentation on the overload taking a ref bool
parameter:
If the lock was not taken because an exception was thrown, the variable specified for the lockTaken parameter is false after this method ends. This allows the program to determine, in all cases, whether it is necessary to release the lock.
But the documentation also states that the overload taking only the object
parameter throws no exceptions other than ArgumentNullException
. So it seems like if an exception were thrown in code snippet 1 above, it could only be because lockObject
is null
, in which case no lock was taken (and TryEnter
would've returned false
) anyway, so the Monitor.Exit
call would not be needed.
Clearly they would not have introduced this overload for no reason. So what scenario is the Monitor.TryEnter(object, ref bool)
method intended to address?
See: Locks and exceptions do not mix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With