The ConcurrentBag<T>
does not provide the functionality that you are looking for. It's not a list, it's a bag. You can't control the order of its contents, and you can't even remove a specific item from this collection. All that you can do is to Add
or Take
an item.
The rich functionality that you are looking for is not offered by any concurrent collection. Your best bet is probably to use a normal List<T>
protected with a lock
. Just make sure that you never touch the List<T>
outside of a protected region. Whether you need to Add
, or Insert
, or Remove
, or enumerate, or read an item, or read the Count
, or anything else, you must always do it inside a lock
region that is locked with the same object.
As a side note, it is quite likely that what you are trying to do is fundamentally wrong. There is a reason that the functionality you are asking for is not available: It's practically impossible to use it in a meaningful way without introducing race-conditions. For example two threads could independently figure out that they must insert a new item in the index 5, based on the existing values in the list, and then both try to inserting it at this index, concurrently. Both will succeed, but one of the two items will end-up in the index 6 after being pushed by the other item, and the two items might not be in the correct order in respect to each other.