Graviton
Graviton

Reputation: 83284

SyncRoot for IList

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
?

Upvotes: 1

Views: 2816

Answers (3)

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

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.

Upvotes: 1

Benjamin Podszun
Benjamin Podszun

Reputation: 9837

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)
    }
  }
}

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166486

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

Upvotes: 6

Related Questions