Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how can I safely exit a lock with a try catch block inside?

Tags:

c#

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?

like image 261
Justin Tanner Avatar asked Mar 12 '09 16:03

Justin Tanner


People also ask

What is '~' in C language?

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 ...

What does the || mean in C?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.


2 Answers

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.
}
like image 45
Michael Avatar answered Sep 26 '22 03:09

Michael


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.

like image 192
Mykola Golubyev Avatar answered Sep 24 '22 03:09

Mykola Golubyev