I am pretty new to multi-threading in general and I would like to know how can I lock a shared integer variable to not be accessed by other threads while it is read/updated by an other thread.
When I try do do SyncLock myInteger
, I get that error : Error 6 'SyncLock' operand cannot be of type 'Integer' because 'Integer' is not a reference type.
Here a simplified example of what I mean
Private Shared myInteger As Integer
Private Sub MySub()
SyncLock myInteger ' This does not work
' read/write a new value to myInteger
End SyncLock
End Sub
MySub is called by multiple instances of the class, and running in multiple threads
I suspect you don't fully understand what SyncLock
does. Even if you could do it (if Integer
were a reference type, for example) you wouldn't want to do it - because when you replaced the value of myInteger
, the lock would be useless.
You should either lock on something else (personally I generally declare a separate, read-only variable purely for the sake of locking, usually of type Object
) or if you only want to operate on myInteger
at any time (rather than some compound operation which needs to read or update several variables at the same time), use the Interlocked
class.