Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I control the order in which event handlers are fired?

Tags:

Are event handlers fired in the order that they attached to the event? If not, can I enforce some kind of order onto the event handlers such that they are called in a specific order?

like image 933
Mike Minutillo Avatar asked Nov 05 '08 02:11

Mike Minutillo


People also ask

What can trigger execution of the event handler?

Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, or by registering the handler as a listener for the element using the addEventListener() method.

What is an event handling and how it can be handled?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events.

How do event handlers behave?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.

How do you edit an event handler?

In the Project Explorer, right-click the form and in the shortcut menu, click Edit event handlers. The form will be selected in the Event Handler editor. In the Form menu in the Form Editor, click Edit event handlers.


2 Answers

Assuming a simple implementation of the event (using += and -= on a delegate field, which in turn will use Delegate.Combine/Remove) then yes, the event handlers will be called in the order in which they're subscribed. The guarantee is effectively given in the Delegate.Combine documentation:

Return value

A new multicast (combinable) delegate with an invocation list that concatenates the invocation lists of a and b in that order.

See my article about events for some examples of which Delegate.Combine/Remove do (and what events are like under the covers).

like image 195
Jon Skeet Avatar answered Sep 23 '22 11:09

Jon Skeet


Do NOT rely on event ordering. All event dispatches should be logically independent, as if they were occurring in parallel.

The addition of event handlers in other classes and threads may disturb your assumed ordering, this is just not a safe assumption to make, and it goes against the concept of events as independent decoupled actions.

I'll go one step further, and assert that if you have to assume an order for events firing, you have a serious design flaw and/or are misusing events.

like image 43
Steven A. Lowe Avatar answered Sep 25 '22 11:09

Steven A. Lowe