Event raising in a new thread in VB.NET

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

(I do not think that the reason for this is relevant, but just in case: I will raise events from code in the form of WndProc sub. If the code that processes the event blocks something in the form [for example, msgbox], then there are all kinds of problems with disconnected contexts and what not. I confirmed that raising events in new threads fixes the problem.)

This is what I am doing now:

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?

As far as I understand, events in VB actually consist of delegates in the background. Is there a way to raise events in new threads without creating a subsystem for each? Or is there a more suitable method that I should use?

+4
source share
2 answers

You can exclude Sub RaiseMyEvent as follows:

 Public Class Class1 Public Event MyEvent() Sub Demo() Dim t As New Threading.Thread(Sub() RaiseEvent MyEvent()) t.Start() End Sub End Class 
+4
source

I don’t know if this will help, but I will always do threads and events like this:

 Event MyEvent(ByVal Var1 As String, ByVal Var2 As String) Private Delegate Sub del_MyEvent(ByVal Var1 As String, ByVal Var2 As String) Private Sub StartNewThread() 'MAIN UI THREAD Dim sVar1 As String = "Test" Dim sVar2 As String = "Second Var" Dim oThread As New Threading.Thread(New Threading.ParameterizedThreadStart(AddressOf StartNewThread_Threaded)) With oThread .IsBackground = True .Priority = Threading.ThreadPriority.BelowNormal .Name = "StartNewThread_Threaded" .Start(New Object() {sVar1, sVar2}) End With End Sub Private Sub StartNewThread_Threaded(ByVal o As Object) 'CHILD THREAD Dim sVar1 As String = o(0) Dim sVar2 As String = o(1) 'Do threaded operation Threading.Thread.Sleep(1000) 'Raise event RaiseEvent_MyEvent(sVar1, sVar2) End Sub Public Sub RaiseEvent_MyEvent(ByVal Var1 As String, ByVal Var2 As String) If Me.InvokeRequired Then 'Makes the sub threadsafe (Ie the event will only be raised in the UI Thread) Dim oDel As New del_MyEvent(AddressOf RaiseEvent_MyEvent) Me.Invoke(oDel, Var1, Var2) Exit Sub End If 'MAIN UI THREAD RaiseEvent MyEvent(Var1, Var2) End Sub 
+4
source

Source: https://habr.com/ru/post/1396115/


All Articles