Locking and throwing?

S

Sonnich Jensen

Is this allowed?

lock(something)
{
throw new exception("Hello world");
}

will the lock be opened, or should I have my throw afterwards?
 
J

Jeff Johnson

Is this allowed?

lock(something)
{
throw new exception("Hello world");
}

will the lock be opened, or should I have my throw afterwards?

Since the throw will exit the procedure (and therefore the scope of the
lock) I can't see why the object would still be locked. But then I'm no
threading expert....
 
J

James A. Fortune

Is this allowed?

lock(something)
{
    throw new exception("Hello world");

}

will the lock be opened, or should I have my throw afterwards?

I have a vague impression that someone at Microsoft recommended not
putting a lock around something that can throw an exception, but it
was parenthetical to the discussion. I think it would have been in
one of the last two PDC08 presentations I viewed about parallelism -
SYMP01 or SYMP03. I'll try to track it down if I'm able. I'm sorry I
can't be more precise. One mentioned a Microsoft blog about
parallelism that could be used to raise a discussion about the issue.

James A. Fortune
(e-mail address removed)
 
J

James A. Fortune

Practically the entire point of the "lock" statement is to ensure that
the lock is _not_ held in the event of _any_ early exit from the method,
including due to an exception.

Otherwise, it wouldn't be any different than:

   Monitor.Enter(something);
   // some code
   Monitor.Exit(something)

…which is not all that useful.

In fact, the "lock" statement is essentially a short-hand way of writing
this:

   object o = something;
   Monitor.Enter(o);
   try
   {
     // some code
   }
   finally
   {
     Monitor.Exit(o);
   }

So, no…do not worry at all about throwing or any other kind of early
return from the method from within a "lock" statement.  It works fine.

See also the "using" statement, which provides similar reliability for
dealing with objects that implement IDisposable.

Pete

Thanks Peter. Now I don't have to look through those presentations
again, plus I doubt I'll ever forget that locks always release upon
early exit similar to how 'using' automatically takes care of
IDisposable. A little egg on the face can be a great mnemonic
device :). You certainly understand well how lock works.

James A. Fortune
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top