【发布时间】:2021-02-25 05:33:18
【问题描述】:
需要从外部工作线程调用编写在 form1 块中的子代码。这是我写的:
在表格 1 中:
Public Delegate Sub UpdateControlDelegate(ByVal C As Label, ByVal txt As String)
Private Sub UpdateControl(ByVal C As Label, ByVal txt As String)
If C.InvokeRequired Then
C.Invoke(New UpdateControlDelegate(AddressOf UpdateControl), New Object() {C, txt})
Else
C.Text = txt
End If
End Sub
Public Sub DoStuff()
'we do some stuff then when it comnes time update a certain control:
Call UpdateControl(MyLabel, "My Text For The Label)
End Sub
在位于类中的workerThread中:
Public Class MyClass
Public Sub UpdateData
Call Form1.DoStuff
End Sub
End Class
这看起来正确吗?关于我想要实现的最简单的术语:
WorkerThread 调用位于 Class Form1 中的 Sub 并且该子包含更新 Form1 中的几个控件的代码。
【问题讨论】:
-
第二个代码 sn-p 在哪里?如果它在
Form1中,那么您应该使用Me而不是Form1。后者使用默认实例,这是特定于线程的。 -
@jmcihinney,感谢您对我所有问题的帮助。第二个 sn-p 位于另一个类中。
-
将Progress<T> 委托传递给工作线程。调用其Report 方法将值传递给委托。实际的委托是您在 UI 线程中声明的
DoSomeStuff()方法。删除Public Delegate Sub DelegateOfDoSomeStuff()。 -- 这里的第一个例子:Start a Task in the Form Shown event -
您可以在该类中使用
SynchronizationContext,然后使用它来编组该类中的 UI 线程。此时,您可以使用Form1的默认实例,如果这确实是已经显示的实例,例如它是启动形式。 -
Form1 在工作线程中不起作用,您将获得 Form1 class 的新 instance。你看不到它,它的 Show() 方法从未被调用过。做对了,但如果你绝对必须使用 Application.OpenForms(0).Invoke
标签: vb.net multithreading