由于某种原因,我无法在调用Thread.Join()时让线程结束。我疯了吗?
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
答案 0 :(得分:1)
这是我跑过的测试,略有修改。
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
答案 1 :(得分:0)
您尚未同步_continue
的访问权限。出于这个原因,它可能是由JIT注册的。在阅读之前和写完之后,同步对它的访问(例如使用Thread.MemoryBarrier
)。
不同步共享数据始终是一个红旗。是因为程序变得越来越糟糕或是因为大多数人都不能很好地理解规则以确保它是安全的(我当然不这样做 - 所以我不这样做)。