简体   繁体   English

如何同时处理集合中的n个项目

[英]How to process n items in a collection concurrently

i am building a class that inherits from List. 我正在建立一个从List继承的类。 Items are going to be added to this collection at runtime and what i want is to have this class automatically do something with each block of n items after they have been added. 将要在运行时将项目添加到此集合中,而我想要的是让此类在添加n个项目的每个块后自动对其进行处理。

So here is the scenario. 所以这是场景。

1] Create new class that inherits from List - CollectionX 1]创建从列表继承的新类-CollectionX

2] At runtime we will be calling ColX.Add(T) many times 2]在运行时,我们将多次调用ColX.Add(T)

3] When ColX has 500 or more items it is to move them into a temporary area and do work on them, then delete them. 3]当ColX有500个或更多项目时,是将它们移到临时区域并对其进行处理,然后将其删除。 Keeping in mind that all the while items will still be being added to ColX. 请记住,所有while项目仍将添加到ColX。

So i guess my question is how do i implement this nicely and by ensuring that it is thread safe. 所以我想我的问题是如何很好地实现这一点并确保它是线程安全的。

The work that is to be performed must be done in blocks so i dont think a queue will work as you can only dequeue 1 item at a time. 要执行的工作必须分块完成,因此我不认为队列可以工作,因为您一次只能使1个项目出队。

I think im looking for more of a pattern than actual types or libraries. 我认为即时通讯正在寻找比实际类型或库更多的模式。

Can anyone help? 有人可以帮忙吗?

Don't let CollectionX inherit from List. 不要让CollectionX从List继承。

Instead, use 2 Lists internally, Add() to 1 and process the other. 而是在内部使用2个列表,将Add()设置为1,然后处理另一个。

This way you only have to lock the swapping of the Lists. 这样,您只需要lock列表的交换即可。 If there are timing problems you could even use a 3rd List to prevent blockage. 如果出现时间问题,您甚至可以使用第三个列表来防止阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM