浏览*更改* ListView 中的每个选定项目
这是我用来浏览 listView 中每个项目的代码:
for (int i = 0; i < listView.SelectedItems.Count; i++) {
MessageBox.Show(listView.SelectedItems[i].SubItems[0].Text);
}
我的问题是,如果 listView 中的项目发生变化,这是否仍然有效。例如,假设我选择了 listView 中的所有项目,然后按下运行上面代码的按钮。当代码运行时,假设 listView 更新,并且其中一项被删除。代码还能成功运行吗?
This is the code I use to go through each item in a listView:
for (int i = 0; i < listView.SelectedItems.Count; i++) {
MessageBox.Show(listView.SelectedItems[i].SubItems[0].Text);
}
My question is if this will still work if the items in the listView changes. For instance, let's say I have all of the items in my listView selected, and press a button that runs the code above. While the code is running, let's say the listView updates, and one of the items is removed. Will the code still run successfully?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有可能该项目在允许另一次迭代的循环条件之后以及在下一行中访问该项目之前被删除。
鉴于此,这不是我所说的可靠代码。您应该确保线程不会尝试同时访问相同的资源,我建议使用互斥锁或使用关键部分。
There is a chance that the item is removed just after the condition of the loop allowed for another iteration and before the item is accessed in the following line.
Given that, this is not what I would call reliable code. You should make sure that the threads do not attempt to access the same resource at the same time, I'd recommend a mutex or using critical sections.
首先,您应该使用 foreach。但是,“成功”迭代取决于您的定义。如果在 foreach 迭代的中间,列表发生更改,它将引发异常。如果您使用已有的基本整数索引,则不会抛出异常,但行为可能是不可预测的。我将使用某种线程同步(例如互斥体)来确保您可以成功地使用 foreach 进行迭代,而不必担心列表发生变化。
First of all, you should be using a foreach. However, "successful" iteration depends on your definition. If, during the middle of a foreach iteration, the list is changed, it'll throw an exception. If you use a basic integer index as you already have, no exception will be thrown but the behaviour could be unpredictable. I would use some sort of thread synchronization like a mutex to make sure that you can successfully iterate with a foreach without worrying about the list changing.