Assuring multicast delegate execution list order in C#?

Deadly 提交于 2019-12-19 07:48:31

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/13759841/assuring-multicast-delegate-execution-list-order-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!