BackgroundWorker更改标签多线程VB.NET

时间:2017-05-04 09:53:54

标签: vb.net multithreading backgroundworker

我是多线程和背景工作者的新手。 我试图根据教程和论坛帖子编写一个简单的测试,但它没有按照我的预期工作。

我有一个带有Button1Label1BackgroundWorker1控件的Windows窗体应用程序。

当我点击按钮时,我想这样做:

  • 后台工作人员连续检查变量state是或否
  • 首先将标签文本更改为False(第一次状态= false)
  • 如果在主线程中将state设置为True,则将标签文本更改为True(“{1}}在”示例流程“(For Next)结束时设置为True)

我的代码是:

state

我的问题是:

  • Label的文本在开头时不会更改为False Public state As Boolean Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Debug.Print("Button1_Click ThreadID - " & Thread.CurrentThread.ManagedThreadId) state = False BackgroundWorker1.RunWorkerAsync() '--Sample process in the main thread For c = 0 To 10000 Debug.Print(c) Next state = True End Sub Dim c As Integer Public Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork setlabel(state.ToString) Do While state = False Debug.Print("BackgroundWorker1_DoWork ThreadID - " & Thread.CurrentThread.ManagedThreadId & " - state: " & state) Thread.Sleep(100) Loop setlabel(state.ToString) End Sub Public Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted Debug.Print("BackgroundWorker1_RunWorkerCompleted - State: " & state) End Sub Sub setlabel(text As String) Label1.Invoke(Sub() Label1.Text = text End Sub) End Sub
  • {li}在BackgroundWorker1_DoWork中没有Do While

输出结果为:

Debug.Print

我错了什么?

1 个答案:

答案 0 :(得分:0)

您正在使用For循环捆绑UI线程:

For c = 0 To 10000
    Debug.Print(c)
Next

您需要让UI线程空闲以调用setlabel(state.ToString) 来实际更新UI。

因此,在设置state = True之前,您需要等待一段时间(甚至是第二个后台工作人员)等待一段时间。