确保C#中的多播委托执行列表顺序? [英] Assuring multicast delegate execution list order in C#?

查看:777
本文介绍了确保C#中的多播委托执行列表顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过阅读后,我了解到处理程序调用顺序与预订顺序相同,但不能保证.

所以可以说我有:

public event MYDEl ev;

和订户这样做:

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

保存+确保执行列表顺序的最佳实践机制是什么?

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

推荐答案

如果是类似字段的事件,它将按照

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和b的调用列表.

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.

一个恶作剧事件实现的示例:

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!");
    }
}

这就像编写一个属性(例如)从getter返回一个随机数并忽略setter中的值一样.这更多的是理论上的问题,而不是实际的问题.

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.

这篇关于确保C#中的多播委托执行列表顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆