Assuring multicast delegate execution list order in C#?
Asked Answered
S

1

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 ?

Schwing answered 7/12, 2012 at 8:58 Comment(3)
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?Duisburg
possible duplicate of what if I need to execute event handlers in certain order?Hazzard
#1645978 , https://mcmap.net/q/2029959/-prioritising-event-handlersHazzard
B
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.

Bree answered 7/12, 2012 at 9:8 Comment(5)
Jon what do you mean nothing is guaranteed ? can my invocation list be ignored ? can you please explain ?Schwing
@RoyiNamir: If you write a custom event handler, you can do whatever you like. I'll give an example.Bree
Regarding your comment to Rob , I asked this question only yesterday ( in another topic)#13748934 and every answer I got is that the order is not guaranteed. that's why I wrote the first comment in my question.Schwing
@RoyiNamir: Right... except for Simon Bull's answer, which is the correct one. I'm adding a new answer myself with C# specification references.Bree
Thank you for investigating the other question as well ! again - Thank you.Schwing

© 2022 - 2024 — McMap. All rights reserved.