事件订阅者是按照订阅的顺序进行的吗? [英] Are event subscribers called in order of subscription?

查看:109
本文介绍了事件订阅者是按照订阅的顺序进行的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设事件订阅者按照订阅顺序进行调用是否安全?

示例:

Is it safe to assume that event subscribers are called in order of subscription?
Example:

void One(object sender, EventArgs e) {}
void Two(object sender, EventArgs e) {}

event EventHandler foo;

foo += One;
foo += Two;

当事件被触发时,One()是否总是在Two()之前调用?

Is One() always called before Two() when the event is fired?

编辑:

你应该不会依赖它,我只是在想。这个想法是,多播代理与COMMAND模式类似。所以我只是想知道。通常情况下,您将使用一个保持命令顺序的集合,以便您可以执行撤消/重做/任何操作。


You should ofcourse not rely on it, I was just thinking. The idea was, that multicast delegates are similary to the COMMAND pattern. So I was just wondering. Ususally you would use a collection that keeps the order for COMMANDs so you can do undo/redo/whatever.

推荐答案

是的,他们将永远以这个顺序被调用。

Given that implementation, yes, they will always be called in that order.

如果事件实际上使用了一些奇怪而精彩的处理订阅方式,它可以做不同的事情 - 但是正常实现将做正确的事情。

If the event actually uses some weird and wonderful way of handling subscriptions, it could do different things - but "normal" implementations will do the right thing.

要清楚,订阅事件处理程序只是调用适当的添加部分事件。如果事件通过执行以下操作来处理此事:

To be clear, subscribing to an event handler just means invoking the appropriate "add" part of an event. If the event handles this by doing something like:

myHandler += value;

被翻译成

myHandler = Delegate.Combine(myHandler, value);

Delegate.Combine 保证排序。但是,如果您有这样的事件:

and Delegate.Combine guarantees the ordering. However, if you had an event like this:

private LinkedList<EventHandler> eventHandlers = new LinkedList<EventHandler>;

public event EventHandler Foo
{
    add
    {
        eventHandlers.AddFirst(value);
    }
    remove
    {
        // do stuff here too
    }
}

,然后通过执行以下操作来触发该事件:

and then fired the event by doing something like:

foreach (EventHandler handler in eventHandlers)
{
    handler(this, EventArgs.Empty);
}

那么处理程序将以相反的顺序调用。

then the handlers would be called in the reverse order.

摘要:对于所有理智的事件,您可以依靠订购。在理论上,事件可以做他们喜欢的事情,但是我从来没有看到一个不维护适当的顺序的事件。

Summary: For all sane events, you can rely on the ordering. In theory, events can do what they like, but I've never seen an event which doesn't maintain the appropriate ordering.

这篇关于事件订阅者是按照订阅的顺序进行的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆