【问题标题】:Multi-Threading (Calling Sub From WorkerThread)多线程(从 WorkerThread 调用 Sub)
【发布时间】: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


【解决方案1】:

在做了更多的研究之后。我已经想通了。我写的初始代码是正确的。唯一缺少的是对我需要更新的表单的引用。

当需要从工作线程调用的 UI 中运行 SUB 时,这里是 COMPLETE 解决方案:

Public Class MyClass
'working thread is being within the subs of this class
Public MyForm1111 As Form1  '<------ The variable in this class that will reference to the form1 that we need

Public Sub MySubThatIsOnAWorkerThread
MyForm1111.DoStuff  '<==== must call MyForm1111.DoStuff and NOT Form1.DoStuff
End Sub

End Class

The Sub Located In Form1:

Public Class Form1


Public Delegate Sub UpdateControlDelegate(ByVal C As Label, ByVal txt As String) 'Required Delegate
    


Private Sub UpdateControl(ByVal C As Label, ByVal txt As String) 'Sub to update controls
            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() 'the sub we need to call from the worker thread
'do some calculations and code
Call UpdateControl(MyLabel, "Some Text For Label")
End Sub

Private Sub Form1_Load()
MyClass.MyForm1111 = Me  <==== Set the reference here in your Form1_Load
End Sub
End Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2012-01-24
    • 2014-03-25
    • 1970-01-01
    • 2013-07-11
    • 2012-03-17
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多