I have an EventHandler that is invoked asynchronously (using BeginInvoke/EndInvoke).
The EventArgs supplied include an incrementing value.
Events are being raised multiple times in quick succession; the events are raised in order such that their EventArgs value is incrementing for each subsequent invocation.
In a subscriber I'm trying to process these events in the order they were raised and I have a lock in the subscriber to ensure I can only process one event concurrently, however, I have an issue that the locks are not always taken in the order they are requested, leading to the events being processed out of order.
I see here: Does lock() guarantee acquired in order requested? that this is somewhat expected; i.e. that I cannot rely on locks being taken in the order they are requested.
One of the answers to that question directed me to a queued lock implementation here: Is there a synchronization class that guarantee FIFO order in C#?
Before I go down that road, I have three questions:-
- If multiple events are raised (rapidly), will the subscriber's handler always be called in the order the events were raised?
- If I implement a queued lock like the one mentioned above, can I rely on the
Enter()
method being called in the right order? (i.e. is there still a risk that "event 2" will reach thequeuedLock.Enter()
in my subscriber before "event 1", even if "event 2" fired after "event 1"); and - Given the EventHandler needs to be async (to prevent subscribers from blocking the thread), is this just not possible/reasonable with an EventHandler and do I need to implement some sort of separate async event queue?