I setup a test console application using the below code:
using System;
class Program
{
static void Main(string[] args)
{
var myEventGenerator = new EventGenerator();
for (int i = 0; i < 10; i++)
new EventListener(myEventGenerator);
while (Console.ReadLine().Length == 0)
myEventGenerator.TriggerEvent();
}
}
class EventListener
{
private static int numberOfInstances = 0;
private int instanceNumber;
public EventListener(EventGenerator eg)
{
eg.EventHappened += EventHappened;
instanceNumber = numberOfInstances++;
}
void EventHappened(object sender, EventArgs e)
{
Console.WriteLine("Event Caught in Instance " + instanceNumber);
}
}
class EventGenerator
{
public event EventHandler EventHappened;
public void TriggerEvent()
{
Console.WriteLine("Event Begin");
if (EventHappened != null)
EventHappened.Invoke(this, new EventArgs());
Console.WriteLine("Event End");
}
}
And the output of the application is:
Event Begin
Event Caught in Instance 0
Event Caught in Instance 1
Event Caught in Instance 2
Event Caught in Instance 3
Event Caught in Instance 4
Event Caught in Instance 5
Event Caught in Instance 6
Event Caught in Instance 7
Event Caught in Instance 8
Event Caught in Instance 9
Event End
Seems that the event listeners are triggering based on the order that they subscribed to the event.
But what if I don’t want those event listeners to occur in that order? What if I want it to be random? Or, if I want to specify a different order? Is there a way to do that?
There isn’t any way to change the order in which the event handler invokes the events hooked up to it. Check out this page for more info.
Here is the important snippet:
If you want this kind of control, you’ll have to write some sort of class that does it for you.