长话短说,我花了很长时间试图弄清楚如何使用调用和/或委托在使用线程时从单独的类更新用户表单。我很确定这对于有更多经验的人来说是愚蠢而明显的。我知道可能需要委托,但我所有的努力似乎只有在从主线程调用时才有效。我已经在互联网上看了半天,只是有些东西我没有得到。
下面以一些伪代码为例:
此选项有效:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t1 As New Threading.Thread(AddressOf Count)
t1.IsBackground = True
t1.Start(100)
End Sub
Private Sub Count(ByVal Max As Object)
If TypeOf Max Is Integer Then
Count(CInt(Max))
End If
End Sub
Private Sub SetLabelText(ByVal text As String)
If Label1.InvokeRequired Then
Label1.Invoke(New Action(Of String)(AddressOf SetLabelText), text)
Else
Label1.Text = text
End If
End Sub
Private Sub Count(ByVal Max As Integer)
For i = 1 To Max
SetLabelText(CStr(i))
Threading.Thread.Sleep(200)
Next
End Sub
End Class
虽然这(我的 1000 次略有不同的变化之一)没有。实际上,对于这个示例,我只是尝试将其中一个潜艇分离到它自己的类中,但在其他方面与我可以做到的相同:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t1 As New Threading.Thread(AddressOf Count)
t1.Start(100)
End Sub
Private Sub Count(ByVal Max As Object)
If TypeOf Max Is Integer Then
Dim class2 As New class2
class2.Count(CInt(Max))
End If
End Sub
Private Delegate Sub SetTextBoxTextInvoker(text As String)
Sub SetLabelText(ByVal text As String)
'or me.label1, form1.label1 or anything else I can try!
If Me.InvokeRequired Then
Me.Invoke(New SetTextBoxTextInvoker(AddressOf SetLabelText), _
text)
Else
Me.Label1.Text = text
End If
End Sub
End Class
Public Class class2
Sub Count(ByVal Max As Integer)
For i = 1 To Max
form1.SetLabelText(CStr(i))
Threading.Thread.Sleep(200)
Next
End Sub
End Class
据我所知,子“SetLabelText”中的invokerequired 的if 语句似乎永远不会被触发。我最好的猜测是我在检查 invokerequired 参数时没有正确引用用户表单?或者我需要向代表提供其他东西?我只是对弄乱我可能弄错的数百万个小变量感到沮丧。提前感谢您提供的任何帮助,如果您需要更多信息,请告诉我。