Does lock{} work across methods?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tom P.

    Does lock{} work across methods?

    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.
  • Pavel Minaev

    #2
    Re: Does lock{} work across methods?

    On Jul 17, 5:04 pm, "Tom P." <padilla.he...@ gmail.comwrote:
    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.

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Does lock{} work across methods?

      Tom P. <padilla.henry@ gmail.comwrote:
      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.

      --
      Jon Skeet - <skeet@pobox.co m>
      Web site: http://www.pobox.com/~skeet
      Blog: http://www.msmvps.com/jon_skeet
      C# in Depth: http://csharpindepth.com

      Comment

      Working...