我是多线程和背景工作者的新手。 我试图根据教程和论坛帖子编写一个简单的测试,但它没有按照我的预期工作。
我有一个带有Button1
,Label1
,BackgroundWorker1
控件的Windows窗体应用程序。
当我点击按钮时,我想这样做:
state
是或否state
设置为True,则将标签文本更改为True(“{1}}在”示例流程“(For Next)结束时设置为True)我的代码是:
state
我的问题是:
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
BackgroundWorker1_DoWork
中没有Do While
输出结果为:
Debug.Print
我错了什么?
答案 0 :(得分:0)
您正在使用For
循环捆绑UI线程:
For c = 0 To 10000
Debug.Print(c)
Next
您需要让UI线程空闲以调用setlabel(state.ToString)
来实际更新UI。
因此,在设置state = True
之前,您需要等待一段时间(甚至是第二个后台工作人员)等待一段时间。