這是關於鎖定兩個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