J'ai une classe qui contient une liste (de T) utilisée dans une application multithread. J'ai trois méthodes Get, Add et Remove où ceux-ci accèdent et modifient la liste (de T). J'utilisais SyncLock pour verrouiller m_List à chaque fois que je le demandais pour l'objet désiré ainsi que pour ajouter ou supprimer des objets. Cependant, je suis curieux de savoir s'il y a un gain de performance en verrouillant simplement m_List quand j'ajoute un objet ou en supprimant un objet par opposition à la recherche d'un objet désiré?Utilisation de SyncLock pour synchroniser l'accès à la liste (de 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
alors je suppose que j'ai besoin de verrouiller la liste pendant l'itération, c'est-à-dire toutes les requêtes linq que je lance sur la collection? – Achilles
@Achilles: Vous pouvez le verrouiller pendant toute la durée de l'itération, ou prendre une copie dans un verrou et parcourir la copie. –
merci pour l'aide! – Achilles