Here is an example of an exception happening inside a lock, with a try-catch block.
int zero = 0;
int j = 10;
lock (sharedResource.SyncRoot)
{
try
{
j = j / zero;
}
catch (DivideByZeroException e)
{
// exception caught but lock not released
}
}
How do I safely release this lock in the catch?
In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.
The lock won't be released until you pass out of the scope of the lock(sharedResource.SyncRoot) block. lock (sharedResource.SyncRoot) {}
is basically identical to:
Monitor.Enter(sharedResource.SyncRoot);
try
{
}
finally
{
Monitor.Exit(sharedResource.SyncRoot);
}
You can either do the Enter/Exit yourself if you want more control, or just rescope the lock to what you want, like:
try
{
lock(sharedResource.SyncRoot)
{
int bad = 2 / 0;
}
}
catch (DivideByZeroException e)
{
// Lock released by this point.
}
Won't it be released automatically?
From the MSDN lock means
System.Threading.Monitor.Enter(x);
try {
...
}
finally {
System.Threading.Monitor.Exit(x);
}
So you don't have to bother.
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