多播委托的执行顺序

结论:

If you are using multicast delegates, you should be aware that the order in which methods chained to the same delegate will be called is formally undefined. You should, therefore, avoid writing code that relies on such methods being called in any particular order.

执行顺序不确定,不可依赖特定顺序执行操作。



最近有个问题,多播委托的执行顺序是怎样的呢?
对于此问题,我想到的一个执行方案是,自己写个例子,看执行结果。
如果,

  1. 执行结果和委托的添加顺序是一致的,则证明委托是按顺序执行的;
  2. 执行结果和委托的添加顺序是相反的,则证明委托是按逆序执行的;
  3. 执行结果和委托的添加顺序是不确定的,则证明委托方法的执行顺序是不确定的;

但是在寻求理论性答案的时候,发现上述的方法论是错误的。原因如下:

随着.net framework\core的版本不同,测试电脑的不同,各种测试结果均有差异。

所以此类问题的解决方法有以下集中:

  1. 看源码,看具体实现机制
  2. 看权威书籍,如官方文档
  3. 海量实验验证,但此法仍然不能保证得到的结果完全正确。

猜你喜欢

转载自blog.csdn.net/u010178308/article/details/81060839