使用 ObservableCollection与后台线程
微软似乎对 ObservableCollection 有一个很棒的想法。 它们非常适合绑定,并且在 UI 上运行速度非常快。
然而,每次想要调整时都需要上下文切换到调度程序线程似乎有点太多了。 有谁知道使用它们的最佳实践? 是不是简单地在业务层中填充 ICollection 作为消息对象,然后在 UI 层中创建 ObservableCollection? 然后如何处理 UI 上集合的更新?
It seems like Microsoft had a great idea with the ObservableCollection. They are great for binding, and are super fast on the UI.
However, requiring a context switch to the Dispatcher Thread every time you want to tweak it seems like a bit much. Does anyone know the best practices for using them? Is it simply to populate an ICollection as a message object in the business layer, then create the ObservableCollection in the UI layer? How do you then handle updates to the collection on the UI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新 UI 线程上的 ObservableCollection 真的会给您的应用程序造成那么大的瓶颈吗? 如果没有,请坚持在 UI 线程上更新它。 请记住,当您使用 Dispatcher 运行某些内容时,这并不是真正发生的上下文切换 - 相反,您只是将作业提交到 UI 线程,该线程是一个已经在运行的线程,操作系统无论如何都会在某个时刻上下文切换到该线程。 UI 线程将您提交的作业从内部队列中取出并执行。 您不会自己强制上下文切换。
Is updating the ObservableCollection on the UI thread really causing that much of a bottleneck for your application? If not, stick with updating it on the UI thread. Remember, it's not really a context switch that's happening when you run something with the Dispatcher - instead, you're simply submitting a job to the UI thread, which is an already running thread, which the OS will context switch to at some point anyway. The UI thread pulls your submitted job off of an internal queue and executes it. You're not forcing the context switch yourself.
您也可以在 WPF 中使用旧的 BackgroundWorker (如在 Windows 窗体中)。 它将采用 WPF 的线程模型,并提供一个很好的抽象。
You can use good old BackgroundWorker also in WPF (as in Windows Forms). It will adopt to the threading model of WPF and also provide a nice abstraction.