从工作线程引发事件 Vb.net

Raise Event Vb.net from worker Thread

我正在寻找 vb.net 的控制台应用程序。我试图让一个工作线程向主线程引发一个事件以在屏幕上显示数据(每次工作线程完成一个周期时 "HIT" 一词)。我的代码如下。

我不确定为什么主线程的 Private Sub CounterClass_GivingUpdate() Handles _counter.AboutToDistributeNewupdate 没有执行。

Imports System.Threading

Module Module1

    Private WithEvents _counter As CounterClass
    Private trd As Thread
    Sub Main()
        While True

            Dim s As String = Console.ReadLine()
            Dim started As Boolean
            Select Case s
                Case "status"
                    WriteStatusToConsole("You typed status")
                Case "startcounter"
                    If started = False Then
                        starttheThread()
                        started = True
                        WriteStatusToConsole("You Have Started The Timer")
                    Else
                        WriteStatusToConsole("YOU HAVE ALREADY STARTED THE TIMER!!!")
                    End If

            End Select
        End While

    End Sub


    Private Sub CounterClass_GivingUpdate() Handles _counter.AboutToDistributeNewupdate
        WriteStatusToConsole("Hit")
    End Sub

    Private Sub starttheThread()
        Dim c As New CounterClass
        trd = New Thread(AddressOf c.startProcess)
        trd.Start()
    End Sub
    Sub WriteStatusToConsole(ByVal stringToDisplay As String)
        Console.WriteLine(stringToDisplay)
    End Sub
End Module

Public Class CounterClass
    Public Event AboutToDistributeNewupdate()
    Public Sub sendStatusUpdateEvent(ByVal updatestatus As String)
        RaiseEvent AboutToDistributeNewupdate()
    End Sub

    Public Sub startProcess()
        Dim i As Int64
        Do
            Thread.Sleep(1000)
            i = i + 1
            sendStatusUpdateEvent(i.ToString)
        Loop
    End Sub

End Class

你的CounterClass_GivingUpdate()只处理_counter变量的事件(你不用的变量!)。每次你声明一个新的 CounterClass 它都有它自己引发的事件实例。

你知道有两个选择:

  • 选项 1

    为您创建的每个新 CounterClass 实例订阅事件。这意味着每次创建 class:

    的新实例时都必须使用 AddHandler 语句
    Private Sub starttheThread()
        Dim c As New CounterClass
        AddHandler c.AboutToDistributeNewupdate, AddressOf CounterClass_GivingUpdate
        trd = New Thread(AddressOf c.startProcess)
        trd.Start()
    End Sub
    
  • 选项 2

    将事件标记为 Shared 使其可用,而无需创建 class 的实例。为此,您还必须更改订阅事件的方式,方法是在您的方法 Main():

    中订阅它
    Sub Main()
        AddHandler CounterClass.AboutToDistributeNewupdate, AddressOf CounterClass_GivingUpdate
    
        ...the rest of your code...
    End Sub
    
    Private Sub CounterClass_GivingUpdate() 'No "Handles"-statement here.
        WriteStatusToConsole("Hit")
    End Sub        
    
    Public Class CounterClass
        Public Shared Event AboutToDistributeNewupdate() 'Added the "Shared" keyword.
    
        ...the rest of your code...
    End Class