With option 1, note that you have to lock not only on write, but on all reads, otherwise lock is useless. That means reads will block each other, and if going this route – at least user
ReaderWriterLockSlim instead of simple lock.
Option 2 leaves dictionary in inconsistent state (some values are old, some are new) for a brief moment, which also might be a concern, plus
ConcurrentDictionary should have some overhead over regular dictionary (most of the times it’s irrelevant, but who knows your specific use case).
Option 3 should be the fastest. Note that I believe there is no need to use
Interlocked.Exchange, you can just assign:
myDict = LoadDictionary();
But also note that to ensure other threads are not reading some cached value – it makes sense to mark
volatile (which has some quirks, but in your specific use case should work fine).
Then, there is no need to use
ConcurrentDictionary in option 3, because you are never writing to that dictionary (after it’s assigned and available to readers that is). So better make it something like
ReadOnlyDictionary. Reading from multiple threads is safe as long as that dictionary is never modified.
CLICK HERE to find out more related problems solutions.