被称为以订阅事件订阅? [英] Are event subscribers called in order of subscription?

查看:233
本文介绍了被称为以订阅事件订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是安全的假设事件的用户被称为以认购?
例如:

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;

是一()总是叫二()时,该事件被开除了?之前

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

编辑:
你应该ofcourse不依赖于它,我只是在想。当时的想法是,多播代表是类似地到命令模式。所以,我只是想知道。通常游戏,你会使用保持顺序命令的集合,以便你可以做撤销/重做/什么。


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天全站免登陆