Is this code thread-safe? or put it this way:
Is there anyway to call GetIt() and that GetIt() will return the same number to 2 different threads
Private Shared hitCount As Long = 1
Public Shared Function GetIt() As Long
Threading.Interlocked.Increment(hitCount)
DoSomethingQuick(hitCount)
Return hitCount
End Function
It seems like it’s possible, then am I supposed to use Interlocked.Read() or lock the whole thing in one block?
Yes there is a possibility:
Threading.Interlocked.Increment(hitCount)Threading.Interlocked.Increment(hitCount)Return hitCountReturn hitCountIn steps 3 and 4, hitCount will be the same value.
But the fix is easy Interlocked.Increment returns the incremented value, so just change your code to:
Edit
Or now based on your edit, you have a pretty bit timing hole. Anyway then this is what you want:
Edit
Then do this (which is exactly what Michael suggested below)