在多线程应用程序中填充 ListView
我需要从数据库中检索一组数据,然后用这些数据填充 ListView。我了解多线程表单控件以及从工作线程更新控件的正确技术。这是一个困境:
我在 ListView 中可能有几千个条目...而不是调用表单线程一次更新它们,我想构建 ListViewItem 对象的集合并使用 ListView.Items.AddRange(ListViewItemCollection )。
但是,MSDN 文档建议不要创建自己的 ListViewItemCollection(事实上,尝试创建自己的 ListViewItemCollection 会生成空引用错误,因为没有父集)。相反,MS 建议您仅通过 ListView.Items 属性获取 ListViewItemCollection 来使用它。
当然,这是循环推理,并且无法在不生成错误的情况下从工作线程完成:“跨线程操作无效:控制‘ListView’从创建它的线程以外的线程访问。”
我可以使用重载的 AddRange(ListViewItem[]),但在当今时代,数组相当笨重。
有人建议如何从工作线程向 ListView 添加数千个项目吗?
I need to retrieve a set of data from a database, then populate a ListView with the data. I understand multithreaded form controls and the proper techniques for updating controls from worker threads. Here's the dilemma:
I may have several thousand entries in the ListView... rather than Invoking the form thread to update them one at a time, I'd like to build a collection of ListViewItem objects and use ListView.Items.AddRange(ListViewItemCollection).
However, the MSDN documentation advises not to create your own ListViewItemCollection (and indeed, trying to create my own ListViewItemCollection generates a null reference error because there's no parent set). Instead, MS recommends that you only work with a ListViewItemCollection by getting it via the ListView.Items property.
Which, of course, is circular reasoning and can't be done from a worker thread without generating an error: "Cross-thread operation not valid: Control 'ListView' accessed from a thread other than the thread it was created on."
I could use the overloaded AddRange(ListViewItem[]), but arrays are rather clunky in this day and age.
Anyone have a suggestion how to add several thousand items to a ListView from a worker thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你已经有了答案 - AddRange(ListViewItem[])。如果您觉得数组令人反感,您可以使用 List,然后在调用 AddRange 时立即执行 toArray()。
I think you already have your answer - AddRange(ListViewItem[]). If you find arrays distasteful, you can use a List and then do a toArray() right when you call AddRange.