开发者

SyncRoot for IList

开发者 https://www.devze.com 2022-12-14 20:39 出处:网络
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:

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

?


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消