If my use case requires that I may get the old state of the object or the new state, but not a corrupted/inconsistent state, should I still be locking the objects ?
e.g.
Public Class Class1
Private StopFlag As Boolean = False
Private MyQueue As New Queue(Of Something)
Public Sub AddItem(item As Something)
MyQueue.Enqueue(item)
End Sub
Public Sub Start()
DoWork()
End Sub
Public Sub [Stop]()
StopFlag = True
End Sub
Private Sub DoWork()
While Not StopFlag
If MyQueue.Count > 0 Then
Dim item As Something = MyQueue.Dequeue
'do something with this item here..
'I have just put sleep to simulate time spent...
Threading.Thread.Sleep(1000)
End If
Threading.Thread.Sleep(100)
End While
End Sub
End Class
Public Class Something
'stub
End Class
In the code above, there are two candidates for lock - StopFlag
and MyQueue
.
Assume that user is continuously enqueuing items at approximately 0.5 to 1 sec. interval. It really doesn't matter to me whether someone was adding to the queue, when I was trying to dequeue from it (except for a lag of 100ms which is acceptable). This is because the item will get processed in the next loop cycle anyways.
For the same reason, the StopFlag
state doesn't matter. It just may process one or two extra cycles, which is acceptable. This class is part of a service which is rarely stopped, except for maintenance. So putting locks to catch once-in-a-while event seems just like an overkill.
Do I still necessarily need to lock both these objects? Will avoiding use of locks cause problems in this case?
In other words, can my StopFlag
ever have anything other than True or False? And can the MyQueue.Dequeue
ever result into an object which is not a valid instance of Something
class?