Using SyncLock to synchronize access to List(of T)

爷,独闯天下 提交于 2019-12-11 18:28:33

问题


I have a class that contains a List(of T) used in a multithreaded application. I have three methods Get, Add and Remove where these access and modify the List(of T). I was using SyncLock to lock m_List any time I queried it for the desired object as well as when I added or removed objects. However I'm curious as to if there is a performance gain by simply locking m_List when I add an object or remove an object as opposed to when I'm searching for a desired object?

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

回答1:


If you try to iterate over the list and allow another thread to add an entry while you're doing so, you'll get an InvalidOperationException, it's as simple as that. My guess is that's not the behaviour you want.

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



来源:https://stackoverflow.com/questions/4197238/using-synclock-to-synchronize-access-to-listof-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!