tags:

views:

156

answers:

3

My code is old code which uses ArrayList to store elements of collection. I use the m_objects.SyncRoot for locking purpose before delete the object:

        lock(m_objects.SyncRoot) 
        {
            m_objects.Remove(obj);

        }

The issue now is, I now want to change the type of m_objects from ArrayList to List<T>, and I encounter problem with the above code. What is the equivalent of List<T>'s SyncRoot
?

+2  A: 

I think this might be what you are looking for

List<string> list = new List<string>();
lock (((IList)list).SyncRoot)
{
}

Found at C# Generics Recipes—Replacing the ArrayList with Its Generic Counterpart

astander
A: 

As far as I understand the SyncRoot concept is outdated and wasn't used much anyway. Most people went with a lock(){} block instead.

public class SomeClass {
  private readonly object listLock = new object();
  private readonly List<string> yourList = new List<string>();

  public void DeleteItem(string item) {
    lock (listLock) {
      yourList.Remove(item)
    }
  }
}
Benjamin Podszun
+1  A: 

As far as I understand the concept the SyncRoot is just an object used to lock. It is there just to save you from creating an object to lock. So it has to be the same to do

Object m_objectsLock = new Object();

lock(m_objectsLock) 
{
    m_objects.Remove(obj);

}

You have to be sure to use m_objectsLock everywhere where the SyncRoot is used.

SoMoS