C # collection class (HashTable, Dictionary, ArrayList, List) and HashTable thread security

Source: Internet
Author: User
The key/value in HashTable is of the object type and is composed of buckets containing collection elements. A bucket is a virtual sub-group of each element in HashTable. Compared with searching and searching in most sets, a bucket can make searching and searching easier. Each bucket is associated with a hash code. The hash code is generated using a hash function and is based on the key of this element. The advantage of HashTable lies in its indexing method, which is very fast. If any type of key value is used to access the element, it is faster than other sets, especially when the data volume is very large, the efficiency difference is particularly large.

HashTable applications include Object Caching, substitution of tree recursive algorithms, and various scenarios that require efficiency improvement.

// Hashtable sample
System. Collections. Hashtable ht = new System. Collections. Hashtable ();

// -- Be careful: Keys can't be duplicated, and can't be null ----
Ht. Add (1, "apple ");
Ht. Add (2, "banana ");
Ht. Add (3, "orange ");

// Modify item value:
If (ht. ContainsKey (1 ))
Ht [1] = "appleBad ";

// The following code will return null oValue, no exception
Object oValue = ht [5];

// Traversal 1:
Foreach (DictionaryEntry de in ht)
{
Console. WriteLine (de. Key );
Console. WriteLine (de. Value );
}

// Traversal 2:
System. Collections. IDictionaryEnumerator d = ht. GetEnumerator ();
While (d. MoveNext ())
{
Console. WriteLine ("key: {0} value: {1}", d. Entry. Key, d. Entry. Value );
}

// Clear items
Ht. Clear ();

Dictionary is similar to HashTable in internal implementation, but the former does not require packing and unpacking, and the efficiency is slightly higher.

// Dictionary sample
System. Collections. Generic. Dictionary <int, string> fruits =
New System. Collections. Generic. Dictionary <int, string> ();

Fruits. Add (1, "apple ");
Fruits. Add (2, "banana ");
Fruits. Add (3, "orange ");

Foreach (int I in fruits. Keys)
{
Console. WriteLine ("key: {0} value: {1}", I, fruits );
}

If (fruits. ContainsKey (1 ))
{
Console. WriteLine ("contain this key .");
}

ArrayList is a one-dimensional variable-length array with an internal value of the object type. The efficiency is generally:

// ArrayList
System. Collections. ArrayList list = new System. Collections. ArrayList ();
List. Add (1); // object type
List. Add (2 );
For (int I = 0; I <list. Count; I ++)
{
Console. WriteLine (list);
}

HashTable is optimized, and objects that access the underlying object are first hashed, so internal hash is unordered, which ensures high efficiency. That is to say, the output is not in the order of initial addition, the order in which Dictionary traverses the output is the order of addition, which is different from that in Hashtable. To sort HashTable output, you can only implement it by yourself:

// Hashtable sorting
System. Collections. ArrayList akeys = new System. Collections. ArrayList (ht. Keys); // from Hashtable
Akeys. Sort (); // Sort by leading letter
Foreach (string skey in akeys)
{
Console. Write (skey + ":");
Console. WriteLine (ht [skey]);
}

HashTable and thread security:

To ensure thread synchronization access security in the case of multiple threads, Microsoft provides HashTable for Automatic Thread Synchronization:

If HashTable allows concurrent reads but can only be written by one thread, create a HashTable instance as follows:

// Thread safe HashTable
System. Collections. Hashtable htSyn = System. Collections. Hashtable. Synchronized (new System. Collections. Hashtable ());
In this way, if multiple threads attempt to write items in HashTable concurrently, only one thread can write at the same time, and the rest will be blocked; the read threads will not be affected.

Another method is to use the lock statement, but the lock is not HashTable, but its SyncRoot. Although this method is not recommended, the effect is the same, because the source code is implemented as follows:

// Thread safe
Private static Hashtable htCache = new Hashtable ();

Public static void AccessCache ()
{
Lock (htCache. SyncRoot)
{
// Do something
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.