I am explaining one scenario where I replaced the dictionary data structure to Hashtable.
As we know .Net Dictionary keyValuePair<> to iterate through the content. When we use the same in HashTable you will get InvalidCast Exception. the reason is KeyValuePair is meant to be used with Dictionary , and not with Hashtable.
DictionaryEntry can be used with HashTable for iteration with proper casting.
For making HashTable thread safe, there are two alternatives:
1. We can use HashTable.SyncRoot proerpty
1: Hashtable myCollection = new Hashtable();
2: lock(myCollection.SyncRoot)
3: { 4: foreach (object item in myCollection)
5: { 6: // Insert your code here.
7: } 8: }
2. Use the synchronized Wrapper of Hash Table 1: Hashtable myCollection = Hashtable.Synchronized( new Hashtable() );
Even though we use the wrapper there is a problem with hashtable enumeration:
As we know the wrapper allows multiple hashtable read and only one write operation at a time.
In such a case, there is a chance that hash table contents got updated while another thread is enumerating the table content and the enumeration will throw exception.
To avoid such cases, we need to explicitly lock the enumeration codes
1: 1: Hashtable myCollection = new Hashtable(); 2: 2: lock(myCollection.SyncRoot) 3: 3: { 4: 4: foreach (object item in myCollection) 5: 5: { 6: 6: // Insert your code here. 7: 7: } 8: 8: }Thanks!
_mkrs_
great post muralee!
ReplyDelete