Threadsafe Generic Dictionary
-
What is the best way to create thread safe generic dictionary. The only operations done by multiple threads are check if key exists, get value and add value. I created a helper class that calls those methods internally, and uses lock inside the method. Is there a better way of doing it? I know in non-generic versions you could do Hashtable.Synchronized, but generic dictionary doesn't offer this.
-
What is the best way to create thread safe generic dictionary. The only operations done by multiple threads are check if key exists, get value and add value. I created a helper class that calls those methods internally, and uses lock inside the method. Is there a better way of doing it? I know in non-generic versions you could do Hashtable.Synchronized, but generic dictionary doesn't offer this.
A "better" way of doing this would to use the ReadWriterLock, allowing multiple readers but single writers. And yeah, you'll need to implement all the methods yourself. The problem with the built in .Synchronized versions of Hashtable and ArrayList is that naive developers assumed that you could create a synchronized version of the list, have one thread insert an item in the list, and have another thread iterate over it using foreach. BAD PRACTICE! Because using a foreach will iterate over the list without locking it (it can't lock it because it doesn't know when the consumer is done iterating over it). So the insert on another thread interrupts and foreach, causing an exception because the list can't be modified while iterating over the list with foreach. In other words, you can't just assume a synchronized version of your list does takes care of all threading issues. The consumers of the list have to ensure proper synchronization.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango
-
A "better" way of doing this would to use the ReadWriterLock, allowing multiple readers but single writers. And yeah, you'll need to implement all the methods yourself. The problem with the built in .Synchronized versions of Hashtable and ArrayList is that naive developers assumed that you could create a synchronized version of the list, have one thread insert an item in the list, and have another thread iterate over it using foreach. BAD PRACTICE! Because using a foreach will iterate over the list without locking it (it can't lock it because it doesn't know when the consumer is done iterating over it). So the insert on another thread interrupts and foreach, causing an exception because the list can't be modified while iterating over the list with foreach. In other words, you can't just assume a synchronized version of your list does takes care of all threading issues. The consumers of the list have to ensure proper synchronization.
Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango