数据网格绑定 (WPF) 导致 UI 延迟
我希望能够快速将项目添加到数据网格,而不会导致 UI 延迟。
这是我现在正在做的事情: 我正在使用绑定到数据网格的 ObservableCollection。
我使用一个后台线程,仅在从可观察集合中插入/删除时循环并调用当前调度程序上的 Invoke。相反,调用 BeginInvoke 会产生不良结果。
我知道对调度程序调用这么多会导致延迟,但我不知道还能做什么。我以前使用过后台工作人员,但我认为这不适用于我的场景。
我可以做什么来保持 UI 响应能力?
I want to be able to add items to a Data grid at a fast rate without causing UI delay.
Here is what I am doing now:
I am using an ObservableCollection that is bound to the data grid.
I use a background thread that loops and calls Invoke on the current dispatcher only when inserting/removing from the observable collection. Calling BeginInvoke instead has undesirable results.
I know that invoking that much on the dispatcher is causing the delay but I don't know what else to do. I have used background workers before but I don't think that applies to my scenario.
What can I do to keep the UI responsive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
批量更新——后台线程可以将项目添加到队列中,并且您可以通过调用定期刷新绑定的可观察集合。如果您需要处理多线程生产者,请查看 System.Collections.Concurrent 命名空间
Batch the updates -- the background thread could add items to a queue and you can periodically refresh your bound observable collection by invocation. Take a look at the System.Collections.Concurrent namespace if you need to handle multi-threaded producers
设计中的一个主要弱点是,通过绑定到 ObservableCollection,您会导致 UI 渲染添加到列表中的每个项目(可能有数千个)——即使在处理结束时只有 10 个项目需要渲染。呈现。
通过将 ObservableCollection 更改为列表,并在处理结束时手动刷新 DataGrid,我看到了巨大的改进 - 这样 UI 只需要处理 10 个项目。我发现此更改带来了 50% 的性能提升,并且允许 UI 在处理列表时具有 100% 的响应能力。
如果您要长时间处理列表,并且需要显示实时更改,则可以每 100 个项目刷新一次 DataGrid。这将显示大约 0.5 秒精度的结果,这应该足够接近。
A major weakness in your design is that by binding to an ObservableCollection, you are causing the UI to render every item that get's added to the list (possibly thousands) - even if at the end of processing there are only 10 items which need to be rendered.
I saw huge improvements by changing the ObservableCollection to a List, and refreshing the DataGrid manually at the end of processing - this way the UI only ever needs to process 10 items. I found that this change caused a 50% performance gain, as well as allowing the UI to be 100% responsive while the List is being processed.
If you are processing the list for a long time, and need to show live changes, you could refresh the DataGrid every 100 items. This would show results with about 0.5 second accuracy which should be close enough.