这是关于锁定两个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
Run Code Online (Sandbox Code Playgroud)
它驻留在声明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 …
Run Code Online (Sandbox Code Playgroud)