【问题标题】:Throttling incoming messages from real time service to wpf ui限制从实时服务到 wpf ui 的传入消息
【发布时间】:2016-03-05 16:47:52
【问题描述】:

我们以毫秒为间隔从实时服务器获取消息[作为键值对]。

所以基本上,我们发送一个代码列表,每毫秒,我们从实时服务获得响应,作为我们需要在 UI 上显示的键值对(代码价格)。我们正在使用 wpf datagrid 来显示数据。 为了限制传入的消息,我在想如果收到的价格与 UI 上显示的价格相同,我们可以忽略它。因为将所有这些消息刷新到 ui 会降低性能。

此外,我们可能需要一些数据结构来存储传入的消息,然后再将其推送到 UI。您能否建议,在刷新到 UI 之前临时保存这些消息的好的数据结构是什么。

另外,您能否指导我在这种情况下最好的方法是什么?

提前致谢。

【问题讨论】:

    标签: c# wpf multithreading data-binding throttling


    【解决方案1】:

    对于数据和 UI 之间的连接,我将使用一个简单的类作为数据模型,然后使用 MVVM 模型将 ObservableCollection 绑定到您的 wpf DataGrid

    每次收到一个项目时,您都可以将它推送到集合中,setter 可以检查是否需要对集合进行实际更改。

    如果需要,您也可以在将项目添加到集合之前执行此检查。

    非常基本的例子:

    class ViewModel0
    {
        private ObservableCollection<Item> items;
    
        public ObservableCollection<Item> Items
        {
            get { return items; }
            set
            {
                if (//implement check if the new item needs to be pushed to the list here)
                {
                    items = value;
                    NotifyPropertyChanged();
                }
    
            }
        }
    
        public void addNewEntry(string value1, string value2)
        { 
            Item newItem = new Item(value1, value2);
            Items.Add(newItem);
        }
    
        public void addNewEntryWithCheck(string value1, string value2)
        {
            if (//implement check if the new item needs to be pushed to the list here)
            {
                Item newItem = new Item(value1, value2);
                Items.Add(newItem); 
    
            }
        }
    
    }
    

    您也可以丢弃数据模型并直接将 KeyValuePair 实现到您的集合中

    class ViewModel1
    {
        private ObservableCollection<KeyValuePair<string, string>> myVar;
    
        public ObservableCollection<KeyValuePair<string, string>> MyProperty
        {
            get { return myVar; }
            set
            {
                if (//implement check if the new item needs to be pushed to the list here)
                {
                    myVar = value;
                    NotifyPropertyChanged();
                }
    
            }
        }
    
        public void addNewEntry(KeyValuePair<string, string> newEntry)
        {
            MyProperty.Add(newEntry);
        }
    
        public void addNewEntryWithCheck(KeyValuePair<string, string> newEntry)
        {
            if (//implement check if the new item needs to be pushed to the list here)
            {
                MyProperty.Add(newEntry);
            }
        }
    
    }
    

    【讨论】:

    • 感谢您的快速解决方案。但是,消息以每秒 300M 的速度移动。我认为我们可能需要一些限制机制,否则 UI 将继续绘制并且可能没有响应。
    • 只要不做任何改变,NotifyPropertyChanged 就不会被调用,UI 也不会改变。编辑:对于最后一个新条目,最多只能检查 60 次/秒,甚至 5 次。这取决于您认为哪些数据足够重要以显示
    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多