When some thread locks myList in SomeMethodA and while executing the block inside lock, does other thread can execute myList.Add(1) in SomeMethodB or it will wait because ‘myList’ is locked in SomeMethodA?
class A
{
private List<int> myList;
public void SomeMethodA()
{
lock(myList)
{
//...
}
}
public void SomeMethodB()
{
myList.Add(1);
}
}
Edit Explicit answer: No, you need to lock the list explicitely in the
SomeMethodB. The compiler will not automatically add locks for youThe recommended idiom is this:
Beware of exposing finegrained locking like that (you’d typically want to do coarsegrained locking as long as no blocking operations can occur under the lock).
Note Locks in C# are reentrant, though, so calling
SomeMethodBfrom within the lock inSomeMethodAwill not deadlockUpdate Rationale behind using a private lock
objectinstance:See: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
1 (aside from other issues with that approach, such as null values, reference updates, deadlocks etc.)