Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Edit:
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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

that gets translated into

myHandler = Delegate.Combine(myHandler, value);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...