I'm trying to implement this, How to: Declare Custom Events To Avoid Blocking, with more than one custom event. If I duplicate the Public Custom Event section and just change the event's name, then both events are called even if my code only calls one of them. I have made my own modification so that it works with more than one custom event but I think most likely someone else will have a better way of doing.
This is my class' code
Here is the code on form1
The console output when button1 is clicked should be as follows because Test_TestEvent2() has a shorter thread.sleep in it.
This is my class' code
VB.NET:
Public Class TestClass
Private EventHandlerList As New ArrayList
Private EventHandlerIndex As New ArrayList
Public Sub TriggerMultipleEvents()
RaiseEvent TestEvent1()
RaiseEvent TestEvent2()
End Sub
Public Custom Event TestEvent1 As EventHandler
AddHandler(value As EventHandler)
EventHandlerList.Add(value)
EventHandlerIndex.Add("TestEvent1")
End AddHandler
RemoveHandler(value As EventHandler)
EventHandlerList.Remove(value)
EventHandlerIndex.Remove("TestEvent1")
End RemoveHandler
RaiseEvent()
For i As Integer = 0 To EventHandlerList.Count - 1
If EventHandlerList(i) IsNot Nothing Then
If EventHandlerIndex(i) = "TestEvent1" Then
EventHandlerList(i).BeginInvoke(Nothing, Nothing, Nothing, Nothing)
End If
End If
Next
End RaiseEvent
End Event
Public Custom Event TestEvent2 As EventHandler
AddHandler(value As EventHandler)
EventHandlerList.Add(value)
EventHandlerIndex.Add("TestEvent2")
End AddHandler
RemoveHandler(value As EventHandler)
EventHandlerList.Remove(value)
EventHandlerIndex.Remove("TestEvent2")
End RemoveHandler
RaiseEvent()
For i As Integer = 0 To EventHandlerList.Count - 1
If EventHandlerList(i) IsNot Nothing Then
If EventHandlerIndex(i) = "TestEvent2" Then
EventHandlerList(i).BeginInvoke(Nothing, Nothing, Nothing, Nothing)
End If
End If
Next
End RaiseEvent
End Event
End Class
Here is the code on form1
VB.NET:
Imports System.Threading
Public Class MainForm
Public WithEvents Test As New TestClass
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Test.TriggerMultipleEvents()
End Sub
Private Sub Test_TestEvent1() Handles Test.TestEvent1
Console.WriteLine("testevent1 started")
Thread.Sleep(1000)
Console.WriteLine("testevent1 finished")
End Sub
Private Sub Test_TestEvent2() Handles Test.TestEvent2
Console.WriteLine("testevent2 started")
Thread.Sleep(100)
Console.WriteLine("testevent2 finished")
End Sub
End Class
The console output when button1 is clicked should be as follows because Test_TestEvent2() has a shorter thread.sleep in it.
VB.NET:
testevent1 started
testevent2 started
testevent2 finished
testevent1 finished