简体   繁体   中英

How to process n items in a collection concurrently

i am building a class that inherits from 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.

So here is the scenario.

1] Create new class that inherits from List - CollectionX

2] At runtime we will be calling ColX.Add(T) many times

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. Keeping in mind that all the while items will still be being added to 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.

I think im looking for more of a pattern than actual types or libraries.

Can anyone help?

Don't let CollectionX inherit from List.

Instead, use 2 Lists internally, Add() to 1 and process the other.

This way you only have to lock the swapping of the Lists. If there are timing problems you could even use a 3rd List to prevent blockage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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