Lets say I have three different classes that each lock a collection in a slightly different way. Class A directly locks the collection, class B locks the collection's SyncRoot property, and class C uses a dedicated object to lock the collection. My understanding is that the convention is to use one of the last two methods, but I'm curious as to when it's acceptable to use the method class A uses and if there are any potential dangers. Also are there any benefits/dangers between the methods used by classes B and C?
public class A
{
private List<object> _list = new List<object>();
public void DoStuff()
{
lock(_list)
{
...
...
}
}
}
public class B
{
private List<object> _list = new List<object();
public void DoStuff()
{
lock(((ICollection)_list).SyncRoot)
{
...
...
}
}
}
public class C
{
private List<object> _list = new List<object>();
private object _listSyncLock = new object();
public void DoStuff()
{
lock(_listSyncLock)
{
...
...
}
}
}