vb.netmultithreadingraiseevent

Raise Event Vb.net from worker Thread


I'm looking at a console app for vb.net. I'm trying to get a worker thread to raise an event to the main thread to display data on the screen (the word "HIT" everytime the worker thread completes a cycle). My code is below.

I'm not sure why but the main thread's Private Sub CounterClass_GivingUpdate() Handles _counter.AboutToDistributeNewupdate isn't executing.

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

Solution

  • Your CounterClass_GivingUpdate() only handles the _counter variable's event (the variable that you do not use!). Every time you declare a new CounterClass it has its own instance of the event that it raises.

    You know have two options: