A follow-up to this post. My goal is to have only one
Public Sub Calculate(Optional inBack As Boolean = True)
If Not inBack Then
If CalcThread IsNot Nothing Then
CalcThread.Abort() ' yes, I will replace this
CalcThread = Nothing ' XXX
If CalcThread Is Nothing Then
CalcThread = New Threading.Thread(AddressOf InternalCalculate)
CalcThread.IsBackground = True
Private Sub InternalCalculate(Optional Line As Integer = -1, Optional isBack As Boolean = True)
Dim Lock As New Object
Threading.Thread.MemoryBarrier() ' do this BEFORE a write, right?
isRunning = true
'do the expensive stuff
Yes it's safe to use them in single threaded code.
There are issues however with your
InternalCalculate which will allow it to execute code concurrently. Every call to
InternalCalculate creates a new
Synclock will only block threads if these use the same object so make
Lock a readonly member variable.
If you then execute multiple threads then the second, third, fourth etc will wait until the first one to obtain the lock exits the sync lock block. Then the others will go. So if this is code that should only be executed once you should check out the double check lock pattern.
Instead of adding
MemoryBarriers for the reading / writing of volatile data, I'd suggest you use
System.Threading.Thread.VolatileWrite. Then you don't need to remember which order to do your reads / writes in.