我这样做:
Delegate Sub SetTextBoxText_Delegate(ByVal [Label] As TextBox, ByVal [text] As String)
' The delegates subroutine.
Public Sub SetTextBoxText_ThreadSafe(ByVal [Label] As TextBox, ByVal [text] As String)
' InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If [Label].InvokeRequired Then
MsgBox("invoke")
Dim MyDelegate As New SetTextBoxText_Delegate(AddressOf SetTextBoxText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {[Label], [text]})
Else
MsgBox("noinvoke")
[Label].Text = [text]
End If
End Sub
然而它总是使用noinvoke。如果我尝试正常设置它会给我一个线程安全的警告,但不起作用。如果我强制调用然后它说控件没有创建?
有人可以帮忙吗?
答案 0 :(得分:2)
这很可能是因为当您尝试访问控件时尚未创建控件。等到控件加载完毕,或使用Label.Created
进行检查。像这样:
Public Sub SetTextBoxText_ThreadSafe(ByVal Label As TextBox, ByVal text As String) If Label.Created Then If Label.InvokeRequired Then MsgBox("invoke") Dim MyDelegate As New SetTextBoxText_Delegate(AddressOf SetTextBoxText_ThreadSafe) Me.Invoke(MyDelegate, New Object() {Label, text}) Else MsgBox("noinvoke") Label.Text = text End If End If End Sub
P.S。您不需要自定义委托类型,只需使用Action(Of TextBox, String)
即可。您也不需要Label
或text
附近的方括号。