2

I found this part in book "Exam Ref 70-483 Programming in C# - Rob Miles 2nd edition":

Event subscribers
Subscribers bind to a publisher by using the += operator. The += operator is overloaded to apply between a delegate and a behavior. It means “add this behavior to the ones for this delegate.” The methods in a delegate are not guaranteed to be called in the order that they were added to the delegate.

And last sentence in this part is confusing. As far as I know order of invocation list is preserved.
Or I misunderstood it, and this only means that was mentioned in the answer:

In general for events, nothing is guaranteed - it's up to the implementation.

Can someone clarify this?

Alexey Klipilin
  • 1,866
  • 13
  • 29
  • Well, this means that there is probably a *good chance* that handlers *are* called in the order of subscription but it's not 100% as this is not guaranteed and therefore *you* are responsible for making sure that the order is correct (by for example splitting event with 3 handlers to 3 events with one handler and firing them in correct order) – Fabjan Jan 28 '19 at 13:20
  • You should never create or use a delegate where the order of execution would matter. Multicast is rare anyway. – bommelding Jan 28 '19 at 13:48
  • When you implement custom Add() (`+=`) and Remove() (`-=`) [accessors](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-implement-custom-event-accessors), all bets are off. – bommelding Jan 28 '19 at 13:51

1 Answers1

1

My understanding here is indeed that "nothing is guaranteed" in the end.

Yes, it seems that the order of the invocation list (i.e. the list of methods to invoke) is preserved by Delegate.Combine. But if, at the same time, these methods "are not guaranteed to be called in the order that they were added" (to the delegate, i.e. to the invocation list within the delegate), it would seem that no matter how they are ordered in that list, they might be called in any other order.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114