Consider the following code:
static void AddItem()
{
lock (_list)
_list.Add ("Item " + _list.Count); //Lock 1
string[] items;
lock (_list)
items = _list.ToArray(); //Lock 2
foreach (string s in items)
Console.WriteLine (s);
}
If Thread A gets Lock 2, and Thread B attempts to get Lock 1, will B get the lock or not? Considering both locks use the same locking object.
No, thread B will need to wait until thread A releases the lock. That’s the point of it being the same lock object, after all – there’s one lock. Where the lock is acquired or released is irrelevant: only one thread can “own” the monitor at a time.
I would strongly advise you to use braces for readability, by the way: