WPF 和活动对象
我有一个“活动对象”的集合。也就是说,需要定期更新自身的对象。反过来,这些对象应该用于更新基于 WPF 的 GUI。
在过去,我只会让每个对象包含它自己的线程,但这只有在处理具有明确定义的生命周期的有限数量的对象时才有意义。现在我使用的对象仅在表单需要时才存在,因此生命周期是不可预测的。另外,我可以有几十个对象都进行数据库和 Web 服务调用。
正常情况下更新间隔为 1 秒,但由于超时可能最多需要 30 秒。
那么,您会推荐什么设计?
I have a collection of "active objects". That is, objects that need to preiodically update themselves. In turn, these objects should be used to update a WPF-based GUI.
In the past I would just have each object include it's own thread, but that only makes sense when working with a finite number of objects with well-defined life-cycles. Now I'm using objects that only exist when needed by a form so the life cycle is unpredicable. Also, I can have dozens of objects all making database and web service calls.
Under normal circumstances the update interval is 1 second, but it can take up to 30 seconds due to timeouts.
So, what design would you recommend?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以对所有或一组活动对象使用一个调度程序(调度程序)。调度程序可以首先处理高优先级任务,然后再处理其他任务。
您可以查看这篇文章长时间运行的活动对象以及代码以了解如何执行此操作。另外,我建议查看半同步/半异步模式。
如果您有疑问 - 欢迎。
You may use one dispatcher (scheduler) for all or group of active objects. Dispatcher can process high priority tasks at the first place then other ones.
You can see this article about the long-running active objects with code to find out how to do it. In additional I recommend to look at Half Sync/ Half Async pattern.
If you have questions - welcome.
我不是专家,但我只是让对象触发一个事件来指示它们何时发生变化。然后,每当 GUI 收到事件时,它就可以刷新自身的必要部分(使用数据绑定和 INotifyPropertyChanged 时很容易)。
I am not an expert, but I would just have the objects fire an event indicating when they've changed. The GUI can then refresh the necessary parts of itself (easy when using data binding and INotifyPropertyChanged) whenever it receives an event.
如果可能的话,我可能会尝试概括某种数据总线,并且当对象处于“活动”状态时,让它们将自己添加到要更新的对象列表中。如果对象由数据库支持,我特别想使用此模式,因为这样您可以聚合多个查询,而不必为每个对象执行单个查询。
如果最终没有特定对象的侦听器,也没什么大不了的,数据就无处可去。
然后,核心更新程序代码可以使用单个计时器(或多个计时器,或任何适当的计时器)来确定何时获取更新。这样做更多的是数据流,而不是“状态更新”,最终可能会节省很多理智。
I'd probably try to generalize out some sort of data bus, if possible, and when objects are 'active' have them add themselves to a list of objects to be updated. I'd especially be tempted to use this pattern if the objects are backed by a database, as that way you can aggregate multiple queries, instead of having to do a single query per each object.
If there end up being no listeners for a specific object, no big deal, the data just goes nowhere.
The core updater code can then use a single timer (or multiple, or whatever is appropriate) to determine when to get updates. Doing this as more of a dataflow, and less of a 'state update' will probably save a lot of sanity in the end.