0

出于某种原因,我无法在调用 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
4

2 回答 2

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
于 2013-03-23T13:46:33.903 回答
0

您尚未同步访问_continue. 出于这个原因,它可能是由 JIT 注册的。Thread.MemoryBarrier在读取它之前和写入它之后同步对它的访问(例如使用)。

在没有同步的情况下共享数据始终是一个危险信号。是因为程序变得有问题,还是因为大多数人对规则的理解不够好,无法确保它是安全的(我当然不知道——所以我不这样做)。

于 2013-03-23T09:45:27.123 回答