1

If I have:

lock(myLockObject)
{
    mySharedBuffer.Modfiy();
    something.BeginDoStuff(new Action(delegate()
        {
            mySharedBuffer.Modify();
        }));
}

And the callback supplied to BeginDoStuff() is called back on another thread - is the lock held/re-obtained when the callback is eventually run? (I presume the lock is lost and I need to lock again but cannot find the documentation saying so)

2 Answers 2

2

is the lock held/re-obtained when the callback is eventually run?

No - there's no magic going on!

BeginXXX returns immediately and control drops out of the lock block and the lock is released.

If you want to obtain the lock again in the callback, you will need another lock block there.

As with all locking, this means that you have to leave the mySharedBuffer object in a consitent state when the lock is released. Also, this object may be modified by another thread between the time you release the lock after BeginXXX and the time your callback obtains the lock again.


If the implementation of BeginXXX can execute the callback synchronously, then the callstack will be just like normal sequential code and the lock will still be held. In this case, if you try to obtain the lock again in the callback, it will be obtained immediately because Monitor allows recursive lock acquisitions on the same thread.

2
  • out of curiosity: what if the callback complete synchronously on the same thread?
    – markmnl
    Jan 9, 2013 at 12:45
  • I've added this case to my answer. Jan 9, 2013 at 12:51
0

No. Anonymous delegate is not par of lock region.

Usually BeginXXX method perform asynchronous operation, and return immediately. A corresponding EndXXX method is also there to wait for the completion of operation.

If you want to lock anonymous delegate, you need to use nested locking.

lock(myLockObject)
{
    mySharedBuffer.Modfiy();
    something.BeginDoStuff(new Action(delegate()
        {
            lock (myLockObject) // nested locking here
            {
               mySharedBuffer.Modify();
            }
       }));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.