开发者

Using SyncLock to synchronize access to List(of T)

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).Sync开发者_运维知识库Root

         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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜