Form1.vb的
Imports System.Threading
Public Class Form1
Dim demoThread As Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Start As New Class1
Me.demoThread = New Thread( _
New ThreadStart(AddressOf Start.ThreadProcSafe))
Me.demoThread.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Public Sub SetText(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 Me.textBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.textBox1.Text = [text]
End If
End Sub
End Class
Class1.vb
Public Class Class1
Public Sub ThreadProcSafe()
Form1.SetText("This text was set safely.")
End Sub
End Class
有人可以告诉我为什么这不会更新文本框?
当ThreadProcSafe在Form1内部(并且仍然由一个线程启动)被调用时,它可以工作,但是当它被移到另一个类之外时,没有警告或错误,但是没有更新。< / p>
答案 0 :(得分:2)
原因是您指的是第二个代码段中的默认实例。默认实例是特定于线程的,因此第二个代码段将创建Form1
类型的新实例,而不是使用现有实例。您的Class1
需要引用Form1
的原始实例。
如果这不实用,那么解决方案是不在表单中进行委派,而是使用SynchronizationContext
类在访问表单的类中执行。