这是上一个关于锁定两个 List(Of T) 对象的问题的后续。那里的答案很有帮助,但给我留下了另一个问题。
假设我有这样的功能:
Public Function ListWork() As Integer
List1.Clear()
..Some other work which does not modify List1..
List1.AddRange(SomeArray)
..Some more work that does not involve List1..
Return List1.Count
End Function
它驻留在声明 List1 的类中。在多线程环境中,我现在明白我应该为 List1 提供一个私有锁定对象,并在 List1 被修改或枚举时锁定它。我的问题是,我应该这样做:
Private List1Lock As New Object
Public Function ListWork() As Integer
SyncLock List1Lock
List1.Clear()
End SyncLock
..Some other work which does not modify List1..
SyncLock List1Lock
List1.AddRange(SomeArray)
End SyncLock
..Some more work that does not involve List1..
SyncLock List1Lock
Dim list1Count As Integer = List1.Count
End SyncLock
Return list1Count
End Function
或这个:
Private List1Lock As New Object
Public Function ListWork() As Integer
SyncLock List1Lock
List1.Clear()
..Some other work which does not modify List1..
List1.AddRange(SomeArray)
..Some more work that does not involve List1..
Dim list1Count As Integer = List1.Count
End SyncLock
Return list1Count
End Function
我猜前一个例子是最优的?