Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Ordering in .NET

Tags:

c#

.net

events

Got a quick question on event ordering in C#/.NET.

Let's say you have a while loop that reads a socket interface (TCP). The interface is definitely taking care of the ordering (it's TCP). Let's say your packet interface is written so that each "packet" you get in the stream, you will forward it to the next "layer" or the next object via an event callback.

So here is the pseudocode:

while (1) {
    readsocket();
    if (data received = complete packet)
        raiseEvent(packet);
}

My questions are:

  1. Are the events generated in order? (i.e. preserve ordering)
  2. I am assuming #1 is correct, so that means it will block the while loop until the event finishes processing?
like image 449
Tony Avatar asked Jan 27 '26 23:01

Tony


1 Answers

You never know how the event is implemented. It's possible that the events will all be executed synchronously, in order, and based on some meaningful value. It's also possible that they'll be executed synchronously in some arbitrary and inconsistent ordering. It's also possible that they won't even be executed synchronously, and that the various event handlers will be executed in new threads (or thread pool threads). It's entirely up to the implementation of the event to determine all of that.

It's rather uncommon to see different event handlers executed in parallel (and by that I mean very, very very rare), and almost all events that you come across will be backed by a single multicast delegate, meaning the order they will be fired in is the order in which they were added, but you have no way of actually knowing if that's the case (baring decompiling the code). There is no indication from the public API if that is how it is implemented.

Regardless of all of this, from a conceptual perspective, it would be best to not rely on any ordering of event handler invocations, and it's generally best to program as if the various event handlers could be run concurrently because at a conceptual level, that is what an event represents even if the implementation details are more restrictive.

like image 111
Servy Avatar answered Jan 29 '26 12:01

Servy