Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable to Dictionary<> syncroot .

Hashtables have a syncroot property but generic dictionaries don't. If I have code that does this:

lock (hashtable.Syncroot)
{
....
}

How do I replicate this if I am removing the hashtable and changing to generic dictionaries?

like image 749
leora Avatar asked Nov 29 '08 16:11

leora


People also ask

What is faster in C#: dictionary or hashtable?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

What is the difference between hashtable and dictionary?

In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.

Is hashtable type safe C#?

C# Hashtable class is a collection class where we can store data in the key/value pair. Hashtable is not type-safe.

What is TKey C#?

The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System. Collections. Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values.


2 Answers

If you are going strictly for compatability then Bryan is correct. This is the best way to maintain your current semantics on top of a Dictionary.

Expanding on it though. The reason the SyncRoot property was not directly added to the generic dictionary is that it's a dangerous way to do synchronization. It's only slighly better than "lock(this)" which is very dangerous and prone to deadlocks. Here are a couple of links that speak to why this is bad.

  • http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx
  • http://blogs.msdn.com/ricom/archive/2006/05/01/587750.aspx
like image 95
JaredPar Avatar answered Oct 25 '22 18:10

JaredPar


The new thinking behind SyncRoot is that it was a mistake in the original design. If the only thing to lock is the dictionary and it's private, you can lock it or another object that serves as the synchronization object. The latter technique is useful when the state you are protecting is more than just the dictionary.

// used as you would have used SyncRoot before
object _syncLock = new object();
Dictionary<string, int> numberMapper = new Dictionary<string, int>();

// in some method...
lock (_syncLock)
{
    // use the dictionary here.
}
like image 29
denis phillips Avatar answered Oct 25 '22 17:10

denis phillips