Younghyo Kim Younghyo Kim - 18 days ago 5
C# Question

locking by target object self

I'm curious about the difference below two example.

private readonly object key = new object();
private List<int> list = new List<int>;
private void foo()
{
lock(key){
list.add(1);
}
}


case 1) locking by readonly object

private List<int> list = new List<int>;
private void foo()
{
lock(list){
list.add(1);
}
}


case2) locking by target object itself

are both cases thread-safe enough? i'm wondering if garbage collector changes the address of
list
variable(like 0x382743 => 0x576382) at sometime so that it could fail thread-safe.

Answer

So long as List<T> does not have within its code any lock(this) statements the two functions will behave the same.

However, because you don't always know if a object locks on itself or not without looking through it's source code it is safer to just lock on a separate object.

One thing of note, classes that inherit from ICollection have a SyncRoot property which is explicitly the object you are supposed to lock on if you want to put a lock on the collection without using a seperate object.

private List<int> list = new List<int>;
private void foo()
{
    lock(((ICollection)list).SyncRoot){
        list.add(1);
    }   
}

This internally is just doing the same thing as you did and created a separate new Object() to lock on.

Comments