views:

58

answers:

1

Consider the following code snippet within a class

private static Object _syncroot = new Object();

public void DoSomeWork()
{
  // do some processing code
  lock(_syncroot)
  {
     // process some shared data
  }


  // do some processing code
  lock(_syncroot)
  {
     // do some further processing of shared data
  }

}

If this code is being hit by multiple threads, if thread A gets into the second thread block locking against _syncroot, would this also effectively lock any threads from entering the first sync block until thread A has exited the second sync block?

+4  A: 

Yes. The lock on _syncRoot obtained by Thread A will block Thread B from obtaining a lock on the same object, until Thread A releases it.

If you need concurrent threads to Read from the same object (which is safe, concurrent writes are where things go bad) then look at System.Threading.ReaderWriterLockSlim.

STW
Thanks for the info.
Andrew
no problem, just click the big check-mark if it answered your question :)
STW