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 に答える