0

我有一个包含多线程应用程序中使用的 List(of T) 的类。我有三种方法 Get、Add 和 Remove,这些方法可以访问和修改 List(of T)。每当我查询所需对象以及添加或删除对象时,我都使用 SyncLock 锁定 m_List。 但是,我很好奇当我添加对象或删除对象而不是搜索所需对象时,通过简单地锁定 m_List 是否可以提高性能?

Public Shared sub Add(SomeObject as object)

     SyncLock ctype(m_List, IList).SyncRoot

         m_List.add(SomeObject)

     end SyncLock

end sub

Public Shared sub Remove(SearchString as string)

     SyncLock ctype(m_List, IList).SyncRoot

           m_List.RemoveAll(function(o as SomeObject) o.SomeProperty = SearchString)

     end SyncLock
end Function

Public Shared Function Get(SearchString as string) as SomeObject
     'The Commented out code is what I am thinking of removing...
     'SyncLock ctype(m_List, IList).SyncRoot

     Dim FoundObjectList = m_List.where(function(o as SomeObject) o.SomeProperty = SearchString)

    if FoundObjectList.count > 0 then 

       If FoundObjectList(0).CreateDate < Now.AddMinutes(5) then
          Remove(FoundObjectList(0).SomeProperty)
          Return nothing
       end if
    else
         Return FoundObjectList(0)

    End if

   Return Nothing
'end SyncLock
end sub
4

1 回答 1

6

如果您尝试遍历列表并允许另一个线程在您这样做时添加一个条目,您将得到一个InvalidOperationException,就这么简单。我的猜测是这不是你想要的行为。

List<T> simply doesn't support writing from one thread and reading from another at the same time - particularly not iterating over the list.

于 2010-11-16T17:52:20.463 回答