0
我有一個包含多線程應用程序中使用的List(T)的類。我有三個方法Get,Add和Remove where這些訪問和修改列表(的T)。我在使用SyncLock鎖定m_List時,無論何時查詢所需對象以及何時添加或刪除對象。 然而,我很好奇,當我添加一個對象或刪除一個對象時,只需鎖定m_List,而不是在搜索所需對象時,是否有性能增益?使用SyncLock同步訪問List of(T)
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
所以我認爲我需要鎖定列表,而迭代正在發生,即任何linq查詢我正在對該集合運行? – Achilles 2010-11-16 17:57:32
@Achilles:要麼在整個迭代時間內鎖定它,要麼在鎖中獲取副本並迭代副本。 – 2010-11-16 18:40:32
感謝您的幫助! – Achilles 2010-11-16 19:10:25