我使用以下代码设置了一个测试控制台应用程序:
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");
}
}
应用程序的输出是:
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
似乎事件侦听器是根据他们订阅事件的顺序触发的。
但是,如果我不希望这些事件侦听器按该顺序发生怎么办?如果我希望它是随机的怎么办?或者,如果我想指定不同的顺序?有没有办法做到这一点?