Does lock{} work across methods?

T

Tom P.

I have a class that ahs several methods. It pulls from a queue so it
has to be singleton at that point. The question I have is: does the
lock{} statement work across methods? If I have A(), B(), and C() and
I do this:
A()
{
lock{
SomeWork();
}
}

B()
{
lock{
Some();
Other();
Work();
}
}

Will A() be locked if a thread is currently in B()? Thanks for the
help.

Tom P.
 
P

Pavel Minaev

I have a class that ahs several methods. It pulls from a queue so it
has to be singleton at that point. The question I have is: does the
lock{} statement work across methods? If I have A(), B(), and C() and
I do this:
A()
{
  lock{
         SomeWork();
     }

}

B()
{
     lock{
           Some();
           Other();
           Work();
      }

}

Will A() be locked if a thread is currently in B()? Thanks for the
help.

If both locks are on the same object, and the calls are on two
different threads, then, yes, a call to A on one thread will be locked
while another thread is executing B.
 
J

Jon Skeet [C# MVP]

Tom P. said:
I have a class that ahs several methods. It pulls from a queue so it
has to be singleton at that point. The question I have is: does the
lock{} statement work across methods? If I have A(), B(), and C() and
I do this:
A()
{
lock{
SomeWork();
}
}

B()
{
lock{
Some();
Other();
Work();
}
}

Will A() be locked if a thread is currently in B()? Thanks for the
help.

That entirely depends on what you put in the bit you've missed out. The
"lock" statement works on a reference - it's not

lock {
code
}

it's

lock(reference) {
code
}

If you use the same reference in the two methods, then the lock will
indeed hold across methods.

See http://pobox.com/~skeet/csharp/threads for more info.
 
B

Brian Rasmussen [C# MVP]

Jon has already addressed the question about locks, so I'll just add a bit
of advice. Generally you should try to keep locking to a minimum in order to
increase concurrency and reduce the risk of deadlocks. Locking "around" a
number of method calls could lead to various problems, so please be careful
and make sure to lock for as long as needed but no more.
 

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