What's the best way to add / remove a specific item from a <T> list in a multi-threaded script
I have a script that needs to add and remove items in a multi-threaded state
I do
lock(list) { if(!list.Contains(item)) { list.Add(Item); } } and
lock(list) { if(list.Contains(item)) { list.Remove(Item); } } But now I have a very big problem with the state of the race. The lock time increases and increases.
I would like to use the ConcurrentBag, but it does not have the Contains Method, so I cannot delete the specific element that I want to delete.
Now I am using ConcurrentDicionary as a workaround. but this is definitely not the right way to do it.
So my question is, how can I solve this problem? Is there any lock for such things? Because none of the collections under the parallel namespace are suitable for this problem.
What you want is a parallel version of HashSet<T> . ConcurrentBag<T> not intended to do this, to support effective producer-consumer scenarios. There is no such collection in the Framework.
So, you could use ConcurrentDictionary<Item, Item> , as you said. But I agree with you that this is not an ideal solution.
Or you can replace the lock code that uses List<T> with one that uses HashSet<T> . Operations like Contains() and Remove() can be very slow on large lists. But they should be fast in hash sets, which should greatly improve your performance if your collection is large enough.
It may also be a third-party library that contains something like ConcurrentHashSet<T> , but I don't know anything about it.