c# - How do you guarantee sequential execution of async event handlers? -
conventional wisdom async void
ok in event handlers works great in gui-driven applications (e.g. wpf).
however, i've been bitten assumption when working different sort of event handlers. consider application event handler gets called result of external event, such rabbitmq message or third party integration library. presumably, event handler gets called kind of dispatcher loop.
if code in event handler synchronous, - needs finish executing before event handler can fire again. if event handler async void
, each call event handler fire-and-forget, , many execute in parallel.
it case don't want behaviour. example, if processing messages rabbitmq queue, want process messages in order. yet, able await
asynchronous calls.
how can have asynchronous event handlers , yet still have them executed sequentially?
update: came across blog post stephen cleary describes same problem i'm having. however, if understand correctly, suggested use of deferrals assumes have control on event args (which in case don't).
i think event invokator should not care such things. there might multiple subscribers given event, , subscribers might perform asynchronous operation in event handler. don't want wait them all complete before publishing next event, because suppose subscriber handles message in 100ms , subscriber b handles in 10 seconds - waste subscriber time nothing.
instead, solve on subscriber side. in event handler put incoming message in queue , return. meanwhile process queue thread in background, 1 one.
Comments
Post a Comment