这是关于锁定两个List(Of T)对象的previous question的后续操作。答案很有帮助,但给我留下了另一个问题。使用SyncLock的正确方法(一般情况下)
假设我有这样的功能:
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..
Retrun List1.Count
End Function
驻留在声明列表1类。在多线程环境中,我现在明白我应该有一个用于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
Retrun 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
Retrun list1Count
End Function
我猜测,前者的例子是最优的?
我想我现在明白这一点。非常微妙。我应该参加一个课或其他...感谢您的洞察力。 – 2011-01-26 10:09:58