如何在vb.net中一次运行两个进程?

时间:2015-03-12 14:40:42

标签: vb.net

 Imports System.Threading.Thread
 Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer
    While i <= 10
        TextBox1.Text = i.ToString()
        TextBox1.Refresh()
        Sleep(1000)
        i = i + 1
    End While
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim lbl As Label
    Dim matches() As Control
    matches = Me.Controls.Find("Label" & TextBox1.Text, True)
    If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
        lbl = DirectCast(matches(0), Label)
        lbl.BackColor = Color.Yellow
    End If
End Sub
End Class

如果我点击button1,那么它会在一秒钟后在文本框中显示1到10。它工作正常。当textbox.text = 2时单击button1,那时我想按button2。如果我按下按钮2,那么它应该显示label2.backcolor =黄色。标签号是textbox.text。问题是:在按钮1中完成while循环后,只有我可以按下按钮2。完成while循环后,我们只得到label10为黄色。解决方案:我想在结束循环之前单击该按钮2。请给出解决方案。其实我想在textbox1.text中显示哪个数字标签应该是黄色。

2 个答案:

答案 0 :(得分:2)

While中的Button1.Click循环阻止了UI线程,因此在Button2.Click完成之前阻止Button1.Click处理程序。一个简单的解决方案是使Button1.Click Async(假设.NET 4.5+)并使用Task.Delay(1000)代替:

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer
    While i <= 10
        TextBox1.Text = i.ToString()
        TextBox1.Refresh()
        'Sleep(1000)
        Await Task.Delay(1000)
        i = i + 1
    End While
End Sub

这将在Await被击中时释放UI线程。

您也可以使用后台线程,但是您必须确保在UI线程上进行UI更新。

答案 1 :(得分:0)

警告:接下来是可怕的代码(但它有效!)

Private Sub Wait(ByVal time As Integer) 'in milliseconds
    Dim secs As Integer = Environment.TickCount
    While Environment.TickCount < secs + time
        Application.DoEvents()
    End While

End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim i As Integer
    While i <= 10
        Label1.Text = i.ToString()
        Label1.Refresh()
        Wait(1000)
        i = i + 1
    End While
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
    Static toggle As Boolean
    If toggle Then
        Label1.BackColor = Color.Green
    Else
        Label1.BackColor = Color.Blue
    End If
    toggle = Not toggle
End Sub