Đây là lần theo dõi previous question về khóa trên hai đối tượng Danh sách (T). Câu trả lời có ích nhưng để lại cho tôi một câu hỏi khác.Cách thích hợp để sử dụng SyncLock (nói chung)
Giả sử tôi có một chức năng như thế này:
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
mà nằm trong một lớp học mà tuyên bố List1. Trong một môi trường đa luồng, bây giờ tôi hiểu rằng tôi nên có một đối tượng khóa riêng cho List1 và khóa List1 bất cứ khi nào nó được sửa đổi hoặc liệt kê. Câu hỏi của tôi là, tôi nên làm điều này:
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
hay này:
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
Tôi đoán rằng ví dụ trước đây là tối ưu?
Tôi nghĩ rằng tôi đã hiểu điều này ngay bây giờ. Khá tinh tế. Tôi nên tham gia một lớp học hoặc một cái gì đó ... Cảm ơn sự thấu hiểu. –