c# - Is locking some object in one method is also makes it locked in other method? -


when thread locks mylist in somemethoda , while executing block inside lock, other thread can execute mylist.add(1) in somemethodb or wait because 'mylist' locked in somemethoda?

class {     private list<int> mylist;      public void somemethoda()     {        lock(mylist)        {           //...        }     }      public void somemethodb()     {        mylist.add(1);     } } 

edit explicit answer: no, need lock list explicitely in somemethodb. compiler not automatically add locks

  • why ever have explicitely lock otherwise?
  • things horribly slow. far better forbid multi threading lock each object access1

the recommended idiom this:

class {     private list<int> mylist;     private readonly object _lockobject = new object();      public void somemethoda()     {        lock(_lockobject)        {           //...        }     }      public void somemethodb()     {        lock(_lockobject)        {            mylist.add(1);        }     } } 

beware of exposing finegrained locking (you'd typically want coarsegrained locking long no blocking operations can occur under lock).

note locks in c# reentrant, though, calling somemethodb within lock in somemethoda not deadlock

update rationale behind using private lock object instance:

in general, avoid locking on public type, or instances beyond code's control. common constructs lock (this), lock (typeof (mytype)), , lock ("mylock") violate guideline:

  • lock (this) problem if instance can accessed publicly.
  • lock (typeof (mytype)) problem if mytype publicly accessible.
  • lock("mylock") problem because other code in process using same string, share same lock.

best practice define private object lock on, or private static object variable protect data common instances.

see: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx


1 (aside other issues approach, such null values, reference updates, deadlocks etc.)


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -