Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assuring multicast delegate execution list order in C#?

After doing some reading I understand that handlers invocation order is the same order as subscribed but it is not guaranteed .

So lets say I have :

public event MYDEl ev;

and subscribers do :

ev+=GetPaper;
ev+=Print;
ev+=EjectPaper;

What is the best practice mechanism of preserving +assuring the execution list order ?

like image 849
Royi Namir Avatar asked Dec 07 '12 08:12

Royi Namir


People also ask

When multicast delegate is invoked the methods in the list are called in synchronous order?

A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear.

What is multicast delegate?

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. Only delegates of the same type can be combined. The - operator can be used to remove a component delegate from a multicast delegate.

Which are based on delegates and are multicast delegates?

Multicast delegates help to invoke multiple callbacks. Events encapsulate delegate and implement publisher and subscriber model. Events and Multicast are types of delegates. So delegate is the base for events and multicast.

What are events in C# with example?

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.


1 Answers

If it's a field-like event, it will use simple delegate combination as per Delegate.Combine, and that is guaranteed to preserve subscription order. From the docs for the return value:

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

In general for events, nothing is guaranteed - it's up to the implementation. Heck, it could ignore every subscription you ever make. In reality though, any sane implementation will preserve ordering.

EDIT: Sample of a mischievous event implementation:

public class BadEventPublisher
{
    public event EventHandler Evil
    {
        add { Console.WriteLine("Mwahahaha!"); }
        remove { }
    }

    protected virtual void OnEvil(EventArgs e)
    {
        Console.WriteLine("Who cares? Subscriptions are ignored!");
    }
}

This is just like writing a property which (say) returns a random number from the getter and ignores the value in the setter. It's more of a theoretical problem than a real one.

like image 67
Jon Skeet Avatar answered Nov 15 '22 07:11

Jon Skeet