使用SyncLock同步对List(of T)的访问 [英] Using SyncLock to synchronize access to List(of T)
问题描述
我有一个包含在多线程应用程序中使用的List(of T)的类.我有三种获取,添加和删除方法,这些方法用于访问和修改List(of T).每当我为所需对象查询以及添加或删除对象时,我都使用SyncLock锁定m_List. 但是我是否好奇通过添加对象或删除对象时简单地锁定m_List(而不是在搜索所需对象时)来提高性能?
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
推荐答案
如果您尝试遍历列表并在执行此操作时允许另一个线程添加条目,则会得到一个InvalidOperationException
,它是就如此容易.我的猜测是那不是您想要的行为.
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>
根本不支持从一个线程进行写入,而不能同时从另一个线程进行读取-特别是不遍历该列表.
List<T>
simply doesn't support writing from one thread and reading from another at the same time - particularly not iterating over the list.
这篇关于使用SyncLock同步对List(of T)的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!