使用Join()方法进行VB.NET线程而不冻结表单

时间:2017-01-12 22:35:18

标签: vb.net multithreading join

您好我正在使用join方法研究多线程

我正在尝试创建多个线程并按顺序运行线程。

我知道join方法能够连接线程并按顺序运行线程。

但是,表单正在更新文本框,但整个表单已冻结,因此我无法单击表单中的任何按钮

这是我的代码..

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Dim T_List As New ArrayList
    Dim VALE As Integer = 99
    For i = 0 To 2
        VALE = i
        t = New Thread(New ThreadStart(Sub() run_t(VALE, 10 + (5 * VALE))))
        t.IsBackground = True
        t.Start()
        t.Join()
        ' T_List.Add(t)
    Next

End Sub


Private Sub run_t(t_num As Integer, number As Integer)
    For i = 0 To number
        Thread.Sleep(100)
        CounterBox.AppendText("thread : " & t_num & " : " & i.ToString() + vbNewLine)
        If i Mod 2 = 0 Then
            ComboBox1.Items.Add(i)
        End If

    Next
End Sub

我正在检查" STATHREAD" STATHREAD and main threadhttps://msdn.microsoft.com/en-us/library/ms182351.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

然而,STATHREAD似乎不适用于这种情况。

对于没有冻结形式的线程,使用Join方法可以解决什么问题。

2 个答案:

答案 0 :(得分:0)

在VB.Net表格中,我建议你使用BackgroundWorker,这将让你:

  • 启动计算主题
  • 与您的表单进行交互,而不会阻止UI线程。

BackgroundWorker

Thread.Join是一种阻止方法,永远不应该在GUI事件处理程序中使用。

答案 1 :(得分:0)

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Dim tt As New Thread(AddressOf working) : tt.Start()
End Sub

Sub working()
    Dim T_List As New ArrayList
    Dim VALE As Integer = 99
    For i = 0 To 2
        VALE = i
        run_t(VALE, 10 + (5 * VALE))
        
' T_List.Add(t)
    Next
End Sub

Sub run_t(t_num As Integer, number As Integer)
    For i = 0 To number
        Thread.Sleep(100)
        CounterBox.AppendText("thread : " & t_num & " : " & i.ToString() + vbNewLine)
        If i Mod 2 = 0 Then
            ComboBox1.Items.Add(i)
        End If
        
    Next
End Sub