多线程不起作用

时间:2016-10-29 09:46:23

标签: vb.net multithreading

我正在制作一个简单的多线程程序来解释线程的工作。我希望两个计数器同时计数,但它不起作用。

只有在我使用CheckForIllegalCrossThreadCalls = False时才有效。但是,我想以适当的方式进行编程。

代码:

Dim Thread1 As System.Threading.Thread
Dim Thread2 As System.Threading.Thread

Private Delegate Sub SetTeller1()

Private Sub teller1()
    If teller1Label.InvokeRequired Then
        Invoke(New SetTeller1(AddressOf teller1))
    Else
        For i As Integer = 0 To 1000
            teller1Label.Text = i
            Refresh()
        Next
    End If
End Sub

Delegate Sub SetTeller2()

Private Sub teller2()
    If teller2Label.InvokeRequired Then
        Invoke(New SetTeller2(AddressOf teller2))
    Else
        For i As Integer = 0 To 1000
            teller2Label.Text = i
            Refresh()
        Next
    End If
End Sub

Private Sub teller1Button_Click(sender As Object, e As EventArgs) Handles teller1Button.Click
    Thread1 = New Threading.Thread(AddressOf teller1)
    Thread1.Start()
End Sub

Private Sub teller2Button_Click(sender As Object, e As EventArgs) Handles teller2Button.Click
    Thread2 = New Threading.Thread(AddressOf teller2)
    Thread2.Start()
End Sub

1 个答案:

答案 0 :(得分:2)

多线程工作正常,但您没有使用它。你目前在后台线程中唯一做的就是调用Invoke,这意味着你的线程将在几毫秒内退出然后被丢弃。

一旦调用Invoketeller1teller2方法的执行就会移动到UI线程,这意味着它将阻止UI直到执行完成。您只应在更新UI 时调用,并在后台线程中执行所有迭代。

以下是如何更恰当地完成此操作的示例:

Delegate Sub SetTeller1(ByVal Text As String)

Private Sub teller1()
    For i As Integer = 0 To 1000
        SetTeller1Text(i)
    Next
End Sub

Private Sub SetTeller1Text(ByVal Text As String)
    If Me.InvokeRequired Then
        Me.Invoke(New SetTeller1(AddressOf SetTeller1Text), Text)
    Else
        teller1Label.Text = Text
        Me.Refresh()
    End If
End Sub

为了提高可读性,我将Invoke(...)更改为Me.Invoke(...)

此外,我不确定你为什么要调用Refresh(),因为它没有必要,只会导致额外重绘整个容器(猜测这是一个表单)。