Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - Are event subscribers called in order of subscription?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...