开发者

.Net Threading - Will a thread lock all sync blocks for a single locking object

Consider the following code snippet within a class

private static Object _syncroot = new Ob开发者_C百科ject();

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜