5

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 ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 2
    Unless you have a custom event implementation that doesn't rely on Delegate.Combine, don't worry about it. If you're talking of subscribers on different threads, precisely what ordering guarantees do you need? – Ani Dec 07 '12 at 09:05
  • possible duplicate of [what if I need to execute event handlers in certain order?](http://stackoverflow.com/questions/12043317/what-if-i-need-to-execute-event-handlers-in-certain-order) – H H Dec 07 '12 at 17:06
  • http://stackoverflow.com/questions/1645478/order-of-event-handler-execution , http://stackoverflow.com/questions/3364115/prioritising-event-handlers – H H Dec 07 '12 at 17:07

1 Answers1

11

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Jon what do you mean _nothing is guaranteed_ ? can my invocation list be ignored ? can you please explain ? – Royi Namir Dec 07 '12 at 09:12
  • 1
    @RoyiNamir: If you write a custom event handler, you can do whatever you like. I'll give an example. – Jon Skeet Dec 07 '12 at 09:13
  • Regarding your comment to Rob , I asked this question only yesterday ( in another topic)http://stackoverflow.com/questions/13748434/multicast-delegate-weird-behavior-in-c and every answer I got is that the order is not guaranteed. that's why I wrote the first comment in my question. – Royi Namir Dec 07 '12 at 09:17
  • @RoyiNamir: Right... except for Simon Bull's answer, which is the correct one. I'm adding a new answer myself with C# specification references. – Jon Skeet Dec 07 '12 at 09:22
  • Thank you for investigating the other question as well ! again - Thank you. – Royi Namir Dec 07 '12 at 09:24