Should I use lock to update element of ConcurrentBag?
I have following code:
Is it important to use lock here? Is it worth to use Semaphore or Mutex here?
All I want is a thread-safe update
2 Replies
or maybe I should use Interlocked?
I don't understand why ConcurrentBag doesn't have thread-safe update methdo
That's not what how you're supposed to use it
It's intended that you have one or more threads (producers) throwing items into the bag, and one or more threads (consumers) taking items out of the bag for procesing. The bag doesn't have any order, so it's supposed to be for cases where the order of items doesn't matter
The way you're using it, it looks like you want a
ConcurrentDictionary<string, UserConnection>
?
Even with a ConcurrentDictionary, though, it won't protect you if you decide to mutate an item in the dictionary. You'll either have to use a separate lock, or have immutable objects