Are event subscribers called in order of subscription?

前端 未结 5 977
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 16:07

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

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


        
5条回答
  •  庸人自扰
    2020-12-09 16:49

    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 eventHandlers = new LinkedList;
    
    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.

提交回复
热议问题