0

I need to be able to enumerate the collection in any order (foreach) and Add/Remove an item from any thread.

Direct access by index is not needed.

What collection do I use? Simply a List? If so, do I only have to lock on add/remove or do I have to lock on foreach also?

I want the following operations to be available on any thread.

foreach (var item in myCollection)
{
    // myCollection can be returned in any order.
}

myCollection.Add(item)

var success = myCollection.Remove(item) // returns false if the item does not exist in myCollection
Cheetah
  • 13,785
  • 31
  • 106
  • 190

1 Answers1

4

You sould use ConcurrentBag for thread-safe collections, which Represents a thread-safe, unordered collection of objects, which is avaliable since .NET 4.0

note: I can't give more information because I'm not aware of the context, in which you are going to use it. Provide more information for a deeper answer.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
  • I can't remove a specific object though? – Cheetah Jan 10 '13 at 13:10
  • use `TryTake` - `Attempts to remove and return an object from the ConcurrentBag.` – Ilya Ivanov Jan 10 '13 at 13:29
  • But it may not be the object I want to remove! Sorry I didn't make it clear. See my edits to the OP. I want to be able to specify the object that I want to remove. – Cheetah Jan 10 '13 at 13:30
  • 1
    `Remove from any thread` is quite a tricky requirement. You can see no collection from `System.Collections.Concurrent` implements removal by instance, only `Take` and `TryTake` are implemented. I don't know your scenario, but why don't you try to stick with this model? You can see more details on why no removal by instance here http://stackoverflow.com/questions/11695627/concurrent-collection-supporting-removal-of-a-specified-item – Ilya Ivanov Jan 10 '13 at 14:01