Reputation: 9445
For some reason, I cannot get the thread to end when calling Thread.Join(). Am I crazy?
Public Sub StartThread()
_opsthread = New Thread(AddressOf OpsThread)
_opsthread.IsBackground = True
_opsthread.Start()
End Sub
Public Sub StopThread()
_continue = False
_opsthread.Join()
'Application Hangs Here
End Sub
Public Sub OpsThread()
While _continue
Thread.Sleep(1000)
End While
End Sub
Upvotes: 0
Views: 60
Reputation: 11773
Here is the test I ran, slightly modified.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
StartThread()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
StopThread()
End Sub
Dim _opsthread As Threading.Thread
Dim _continue As New Threading.AutoResetEvent(False)
Public Sub StartThread()
_continue.Reset()
_opsthread = New Threading.Thread(AddressOf OpsThread)
_opsthread.IsBackground = True
_opsthread.Start()
End Sub
Public Sub StopThread()
If IsNothing(_opsthread) Then Exit Sub
_continue.Set()
_opsthread.Join()
'Application Hangs Here
' Debug.WriteLine("end")
End Sub
Public Sub OpsThread()
Dim cont As Boolean = False
While Not cont
cont = _continue.WaitOne(1000)
End While
End Sub
Upvotes: 1
Reputation: 171226
You haven't synchronized access to _continue
. For that reason it was probably enregistered by the JIT. Synchronize access to it (for example using Thread.MemoryBarrier
) before reading it and after writing it.
Sharing data without synchronization is always a red flag. Be it because the program becomes buggy or be it because most people do not understand the rules well enough to make sure it is safe (I certainly don't - so I don't do it).
Upvotes: 0