This is a follow-up to a previous question regarding locking on two List(Of T) objects. The answer there was helpful but left me with another question.
Suppose I have a function like this:
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
which resides in a class that declares List1. In a multithreaded environment, I now understand that I should have a private locking object for List1 and lock List1 whenever it's modified or enumerated. My question is, should I do this:
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
or this:
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
I'm guessing that the former example is optimal?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With