开发者

A good way to pool concurrent events

开发者 https://www.devze.com 2023-02-20 23:22 出处:网络
I have an application in C# wher开发者_高级运维e I get update events from my database repository for each update in the database. When large operations are made on the database multiple events are fir

I have an application in C# wher开发者_高级运维e I get update events from my database repository for each update in the database. When large operations are made on the database multiple events are fired and I want to update the GUI of the application when these events are received, but updating the GUI for each update is not exactly optimal.

What is a good way to "pool" events and only react when no more events are coming in, my first idea was to use a timer with a short duration and reset it for each new event received but this seems a bit clunky. Is there a better/faster/simpler way to solve this problem?

I would prefer not to have visible delays during normal updates.


You may be able to consider the Reactive Framwework.

How to throttle event stream using RX?


I think your way would be the way to go. I would write something like a EventAggregator that has a timer. This timer will start when the first event comes in and will be reset each time a new event comes in within the waiting time. If the waiting time is reached it will raise its own event.

But this leads also to some delay when you only have a single event. So be sure where you want such a behaviour. Also be sure that you fire your async event in the right thread or you'll run into Cross-thread exeception. Maybe the article Implementing the Event-based Asynchronous Pattern article can give you some hints on this question. Also take a look into this Timer article to take the correct timer class for your purpose.


Create a separate Thread which waits on a ManualResetEvent. Use a Queue<DbEvent> to enqueue new events. Signal the ManualResetEvent when a new db event arrives.

Remember to lock the queue each time you dequeue or enqueue items.

In this way you can add new db events from several threads and still get a proper handling with one event at a time.


In my opinion a good approach will be:

When the database is updated, do not make the updates on the guy immediately, wait for a short but determined period to see if any more updates on the database are made.After the period has passed the you should commit the updates to the gui. Then your gui will not be updated in real time, but i think a few seconds is not such a big problem(depending of the usage of the api).The nice thing is that you do not need to update the gui at every database update event.

I hope this will help you.

Cheers Vlad.

0

精彩评论

暂无评论...
验证码 换一张
取 消