Frage

I have the following classes

Child class:

public class ChildClass
{
   ...
   private void EventHandler(...);
   ...
}

Parent class:

public class ParentClass
{
   ...
   ChildClass child;
   ...
   private void EventHandler(...);
   ...
}

Both of them have an event handlers on the same event.

The question is in which order those handlers will be called?

War es hilfreich?

Lösung

Important note

Servy has very correctly pointed out that we cannot rule out the possibility that the event in question is owned by a third party and it implements the accessors itself. If that is the case then all bets are off.

The original answer below silently assumes that we are talking about a bog-standard, totally uninteresting event implementation.

Original answer

Events are implemented through delegates.

From MSDN:

A useful property of delegate objects is that multiple objects can be assigned to one delegate instance by using the + operator. The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order.

So the handlers are invoked in the order that you add them to the event.

Andere Tipps

The order in which the delegates are subscribed to, although since it's not properly noted anywhere in the specification (that I know of) that this is expected behaviour, specifically, then relying on such order could be folly, as it could change per implementation.

it will be called int the order they are registered.

While the MSDN documentation clearly states that the multicast delegates invokes the delegates in the order in which they subscribed, that assumes that the subscription order is deterministic, i.e. that you are in a single-threaded environment.

If that is not the case, you may be better off defining two events: a BeforeEventOccurs event and an AfterEventOccurs event. This will give you deterministic control over the order even in a multi-threaded environment.

According to this question event handlers get called in the order they are subscribing to the event.

From Delegates

Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

From How to: Combine Delegates (Multicast Delegates) page;

A useful property of delegate objects is that multiple objects can be assigned to one delegate instance by using the + operator. The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top