-1

I have a Hashset<string> which is accessed by multiple threads. Whenever I read or write to this, I lock it:

lock(lockObj)
{
   myCollection.Add(myString);
}

In general, do I have to do the same when reading from it? Is there any benefit to doing that?

Deane
  • 8,269
  • 12
  • 58
  • 108
  • If you do, you will never have a problem with thread safety in a multi threaded environment. There are other options dependent entirely on your use case – TheGeneral Nov 06 '21 at 03:31
  • Are you asking if there is any benefit at using a `lock` when reading a `Hashset` from multiple threads concurrently, and there is no thread that mutates the `Hashset`? If yes, and assuming that the `Hashset` is not empty, could you clarify how the collection got its values? – Theodor Zoulias Nov 06 '21 at 06:48
  • @TheodorZoulias The hashset is written too, both during init and during execution (during the same timeframe it's being read from), but it's locked every time I write to it. – Deane Nov 06 '21 at 13:47

1 Answers1

1

No, you need to lock them when - besides the read - there is a write.

As long as the collection is not changed, there is no change that can lead to inconsistencies.

I regularly have non-locked multi threaded reads, i.e. on collection containing metadata that an application loads at start and that never changes.

Generally the problem is that for performance (locks are expensive) it is an overhead to lock, and as long as no read happen while writing (those would possibly be inconsistent) - there simply is no need for the overhead.

If you MUST write to it, use a MultipleReaderSingleWriter lock. This allows only one write, but unlimited readers while no writing happens. RTFM for example and method details.

TomTom
  • 61,059
  • 10
  • 88
  • 148