Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising an event on a new thread in VB.NET

I need to raise an event from a form on a new thread.

(I don't believe the reason for this is relevant, but just in case: I'll be raising events from code within a form's WndProc sub. If the code handling the event blocks with something on a form [such as a msgbox], then all sorts of trouble occurs with disconnected contexts and what not. I've confirmed that raising events on new threads fixing the problem.)

This is what I am currently doing:

Public Event MyEvent()

Public Sub RaiseMyEvent()
    RaiseEvent MyEvent
End Sub

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    Dim t As New Threading.Thread(AddressOf RaiseMyEvent)
    t.Start()
End Sub

Is there a better way?

It is my understanding that events in VB are actually made up of delegates in the background. Is there any way to raise events in new threads without creating subs for each? Or, is there a more appropriate method I should be using?

like image 551
Brad Avatar asked Dec 28 '22 06:12

Brad


1 Answers

You can eliminate the RaiseMyEvent sub like this:

Public Class Class1

    Public Event MyEvent()

    Sub Demo()
        Dim t As New Threading.Thread(Sub() RaiseEvent MyEvent())
        t.Start()
    End Sub

End Class
like image 187
Ian Horwill Avatar answered Jan 09 '23 05:01

Ian Horwill