vb.net通过线程给lable.text赋值问题
Me.lblTime.Text="当前时间:"&System.DateTime.Now我用线程给当前页面赋值的时候窗体上并没有值MsgBox(Me.lblTime.Tex...
Me.lblTime.Text = "当前时间:" & System.DateTime.Now
我用线程给当前页面赋值的时候窗体上并没有值
MsgBox(Me.lblTime.Text )是能输出的
'委托执行
Private Sub SetlblTimeText(ByVal Result As String)
Dim d As New SetTextDelegate(AddressOf SetlblTimeText)
Me.Invoke(d, New Object() {Result})
End Sub
Private Sub btn_StartThead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_StartThread.Click
Dim obj As New main
Dim th4 As Thread
th4 = New Thread(New ThreadStart(AddressOf obj.ThreadTimers))
th4.Start()
End Sub
End Class 展开
我用线程给当前页面赋值的时候窗体上并没有值
MsgBox(Me.lblTime.Text )是能输出的
'委托执行
Private Sub SetlblTimeText(ByVal Result As String)
Dim d As New SetTextDelegate(AddressOf SetlblTimeText)
Me.Invoke(d, New Object() {Result})
End Sub
Private Sub btn_StartThead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_StartThread.Click
Dim obj As New main
Dim th4 As Thread
th4 = New Thread(New ThreadStart(AddressOf obj.ThreadTimers))
th4.Start()
End Sub
End Class 展开
1个回答
展开全部
为了线程安全,微软规定线程不能直接访问窗体控件,需要用委托的方式,窗体代码中增加:
Delegate Sub SetTextDelegate(txt As String)
Private Sub SetText(ByVal Result As String)
If Me.lblTime.InvokeRequired Then
Dim d As New SetTextDelegate(AddressOf SetText)
Me.Invoke(d, New Object() {Result})
Else
Me.lblTime.Text = Result
End If
End Sub
然后在线程中需要更改lblTime时,用:
SetText("当前时间:" & System.DateTime.Now)
Delegate Sub SetTextDelegate(txt As String)
Private Sub SetText(ByVal Result As String)
If Me.lblTime.InvokeRequired Then
Dim d As New SetTextDelegate(AddressOf SetText)
Me.Invoke(d, New Object() {Result})
Else
Me.lblTime.Text = Result
End If
End Sub
然后在线程中需要更改lblTime时,用:
SetText("当前时间:" & System.DateTime.Now)
更多追问追答
追问
谢谢你,我在测试的时候出现Me.lblTime.InvokeRequired = false ,请问这个要如何解决,多谢啦
屏蔽这段代码报错:在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
追答
不明白你的问题,=false说明在你调试的时候有别的线程在使用,你直接执行不能执行吗?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询