In a multithreaded application, I have a Dictionary that is accessed by multiple threads for gettinng the value for a specific key. There is also a mechanism using Quartz.Net to update this dictionary. I am trying to find the best way to make the updated Dictionary availiable for reading in a thread safety manner. Initialy I considered a ReadWriterLockSlim as a solution, but as I searched for probable performance penalties it might have I came upon Interlocked.Exchange and an overload that can be used with objects. So my question is, could it be used in this scenario? I present a code sample of it's usage.
Thanks very much
public class SingletonDictionaryHolder
{
private Dictionary<string, Person> MyDictionary;
public Person GetPerson(string key)
{
return MyDictionary[key];
}
public void UpdateDictionary(Dictionary<string, Person> updated)
{
Interlocked.Exchange(ref MyDictionary, updated);
}
}
Edit:
Since there is a downvote, I am adding some more information:
Another relative questions is presentated here: https://softwareengineering.stackexchange.com/questions/294514/does-readerwriterlockslim-provide-thread-safety-and-speed-efficiency-compared-t
Note the paragraph: "If writes are rare, you can probably get much better performance by treating the collection as immutable and producing an entirely new list when it changes. You can then use Interlocked.CompareExchange to update the reference to the list in a thread-safe way. This should prevent readers needing to make a defensive copy (which should be a huge win if reading is more common than writing) and remove the need for locking."
And concearning the Intelocked.CompareExchange method, an insight is presented here: Using Interlocked.CompareExchange with a class
Kindly note that a correct architectural design would be to use a MemoryCache that is thread safe by default and a pub/sub mechanism to reflect changes on the cached items - however it was not designed by me and I doubt that there is hope of change in the near future.