c# - 有没有办法确定 "shuffle"事件监听器的调用顺序?

标签 c# events random event-handling

我使用以下代码设置了一个测试控制台应用程序:

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

似乎事件监听器是根据它们订阅事件的顺序触发的。

但是如果我不希望这些事件监听器按该顺序发生怎么办?如果我希望它是随机的怎么办?或者,如果我想指定不同的顺序?有办法做到这一点吗?

最佳答案

没有任何方法可以更改事件处理程序调用与其关联的事件的顺序。查看this page了解更多信息。

这是重要的片段:

Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. Each method so called is passed the same set of arguments as was given to the delegate instance. If such a delegate invocation includes reference parameters (Section 10.5.1.2), each method invocation will occur with a reference to the same variable; changes to that variable by one method in the invocation list will be visible to methods further down the invocation list. If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

如果您想要这种控制,则必须编写某种类来为您完成此操作。

关于c# - 有没有办法确定 "shuffle"事件监听器的调用顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480911/

相关文章:

c# - 自定义用户控件事件

java - 如何确保按钮上的 Fxml 方法在监听器之前被调用?

python - 如何停止获得重复的随机值?

c# - 如何用C#登录vbulletin论坛?

c# - 可以在 C# 中使用泛型表单吗?

c# - Ajax 上传和 ASP.NET

c# - 如何检测: scrolling - up or down?

jquery - jQuery 中的triggerHandler 与触发器

java - 递归函数中的错误

sql - TSQL RAND() 问题