Question

I am working on a Messenger library. The main class has a Login method. When logging in, all contact list data is downloaded and stored until the Login has completed, at which point I raise a UserAdded event for each user that was downloaded.

Currently I raise the events right at the end of the Login method, one by one. This works, but it means if I perform a lengthy operation inside a UserAdded event handler, the library consumer does not get their events in a timely fashion.

One way around this I can see would be to raise each event asynchronously, but this would thrash the threadpool.

Am I doing it the right way currently? Should I simply make a note in the documentation warning against performing lengthy operations inside event handlers?

Was it helpful?

Solution

Perhaps you might want to change your event handler to simply "enqueue" into a threadsafe queue work items. You can then have a single thread which pumps the queue continuously to actually process the messages. That way the raise happens very quickly and there is only one thread actually processing the queue of work items.

However doing this means you now have to deal with the fact that raising your event does not mean it has been immediately processed, which could affect logic you have in your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top