通过不断变化的集合进行线程化和迭代
在 C#(控制台应用程序)中,我想保存对象的集合。所有对象都是同一类型。 我想遍历集合,调用每个对象上的方法。然后不断地重复这个过程。 然而,在迭代过程中,可以在列表中添加或删除对象。 (对象本身不会被销毁......只是从列表中删除)。 不确定 foreach 循环或其他类似方法会发生什么。 这之前必须已经做过 1000 次了..你能推荐一个可靠的方法吗?
In C# (console app) I want to hold a collection of objects. All objects are of same type.
I want to iterate through the collection calling a method on each object. And then repeat the process continuously.
However during iteration objects can be added or removed from the list. (The objects themselves will not be destroyed .. just removed from the list).
Not sure what would happen with a foreach loop .. or other similar method.
This has to have been done 1000 times before .. can you recommend a solid approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
还有基于复制的方法。
该算法是这样的:
这种方法的优点是您可以在短时间内获取共享集合上的锁定时间(假设共享集合相对较小)。
如果您想要在每个集合项上调用的方法需要相当长的时间才能完成或可能会阻塞,那么在共享锁下迭代的方法可能会导致阻塞想要从共享集合中添加/删除项的其他线程
但是如果该方法您想要在每个对象上调用的速度相对较快,然后在共享锁下迭代可能更可取。
There is also copy based approach.
The algorithm is like that:
The advantage of this approach is that you take the lock on shared collection for small period of time (assuming that shared collection is relatively small).
In case when method that you want to invoke on every collection item takes some considerable time to complete or can block then the approach of iterating under shared lock can lead to blocking other threads that want to add/remove items from shared collection
However if that method that you want to invoke on every object is relatively fast then iterating under shared lock can be more preferable.
这是多线程中同步的经典案例。
唯一可靠的方法和更好的方法是循环和列表中项目的添加/删除之间的同步。
意味着您应该仅在迭代循环结束和开始时允许添加/删除!
像这样的事情:-
This is classic case of syncronization in multithreading.
Only solid approach and better approach would be syncronization between looping and addition/deletion of items from list.
Means you should allow addition/deletion only at end of end and start of iterating loop!
some thing like this:-
当我读到这个例子时,我想到的是你可以使用 C5
TreeSet
/TreeBag
。它确实需要有一种方法来订购您的项目,但Tree
集合的优点是它们提供了Snapshot
方法(C5.5 的成员)。 IPercientSorted
),允许您制作集合状态的轻量级快照,而无需进行完整的复制。例如:
C5 还提供了一种“适用于所有人”的简单方法并且与 .NET 2.0 兼容:
需要注意的是,快照应该被丢弃,否则您将在对基本集合进行后续修改时遭受较小的性能损失。
这个例子来自非常彻底的 C5 Book。
What comes to mind when I read this example is that you could use a C5
TreeSet
/TreeBag
. It does require that there be a way to order your items, but the advantage of theTree
collections is that they offer aSnapshot
method (A member ofC5.IPersistentSorted
) that allows you to make light-weight snapshots of the state of the collection without needing to make a full duplicate.e.g.:
C5 also offers a simple way to "apply to all" and is compatible with .NET 2.0:
It's important to note that the snapshot should be disposed or you will incur a small performance penalty on subsequent modifications to the base collection.
This example is from the very thorough C5 Book.