Use ConcurrentDictionary to replace Hashtable for multi-threaded Object Caching.

Source: Internet
Author: User
Tags tojson

Use ConcurrentDictionary to replace Hashtable for multi-threaded Object Caching.

In the past, most of my base classes used the combination of lock and Hashtable to handle conflicts in multi-thread cache. However, sometimes these two combinations are not satisfactory, occasionally, exceptions that have been added to the set still occur. After multiple parties process the code, the exception is still used. concurrentDictionary multi-thread synchronous dictionary set introduced only after NET 4.0, and the problem is solved smoothly.

1. Use the combination of lock and Hashtable for implementation.

In my base class, build business objects. Generally, use BLLFactory <T>. Instance to obtain the application of the corresponding business objects.

var result = BLLFactory<Customer>.Instance.FindFirst();Console.WriteLine(result.ToJson());

Therefore, after using BLLFactory <T>. Instance to build objects, put them in HashTable. Because multi-thread conflict processing needs to be designed, lock objects must be used for lock processing.

HashTable indicates the set of key/value pairs. In. in the. NET Framework, Hashtable is System. A container provided by the Collections namespace is used to process and present key-value pairs similar to key-value. The key is usually used for quick search, and the key is case sensitive; value is used to store the value corresponding to the key. In Hashtable, key-value pairs are of the object type, so Hashtable can support any type of keyvalue pairs, and any non-null objects can be used as keys or values.

Using this method, we occasionally encounter multi-threaded access conflicts on the Web end. Therefore, we can also use multi-threaded testing code to test and reproduce errors,

            try            {                List<Thread> list = new List<Thread>();                for (int i = 0; i < 10; i++)                {                    Thread thread = new Thread(() =>                    {                        var result = BLLFactory<Customer>.Instance.FindFirst();                        Console.WriteLine(result.ToJson());                        Console.WriteLine();                    });                    list.Add(thread);                }                for (int i = 0; i < list.Count; i++)                {                    list[i].Start();                }            }            catch(Exception ex)            {                LogTextHelper.Error(ex);            }

The error message returned by the tracking code is as follows.

As a result, we can see from the code above that multi-thread conflicts cannot occur even when lock (syncRoot) is used.

 

2. Replace Hashtable with ConcurrentDictionary

ConcurrentDictionary is. one of the thread security sets released by net4.0 is ConcurrentStack, ConcurrentQueue, and other types released together. Their Single-thread versions (thread unsafe, Queue, Stack, dictionary. ConcurrentDictionary <TKey, TValue> can be accessed by multiple threads at the same time, and the thread is secure. Its usage is much the same as that of Dictionary, but there are some more methods. ConcurrentDictionary belongs to the System. Collections. Concurrent namespace.

The System. Collections. Concurrent namespace provides multiple thread security collection classes. When multiple threads concurrently access the set, use these classes to replace the corresponding types in the System. Collections and System. Collections. Generic namespaces..

The ConcurrentDictionary class provides the following methods for processing sets.

public bool TryAdd(TKey key, TValue value)public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue)public TValue this[TKey key] { get; set; }public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)    public TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)public TValue GetOrAdd(TKey key, TValue value)public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)

Use ConcurrentDictionary to replace Hashtable. Let's take a look at the implementation code of the BLLFactory class as follows.

/// <Summary> /// factory class constructed for the business class /// </summary> /// <typeparam name = "T"> Business Object Type </typeparam> public class BLLFactory <T> where T: class {// use the ConcurrentDictionary thread-safe collection class to cache, replacing Hashtable private static ConcurrentDictionary <string, object> conCurrentCache = new ConcurrentDictionary <string, object> (); /// <summary> /// create or obtain the Instance of the corresponding business class from the cache // </summary> public static T Instance {get {string CacheKey = typeof (T). fullName; return (T) conCurrentCache. getOrAdd (CacheKey, s =>{ var bll = Reflect <T>. create (typeof (T ). fullName, typeof (T ). assembly. getName (). name); // create reflection and cache return bll ;});}}}

We can see that the code is much simplified, and the previous multi-threaded test code is used to smoothly obtain data without exceptions.

The Running code can be implemented smoothly without the multi-threaded access exceptions that have occurred before using Hashtable.

The above is the introduction of ConcurrentDictionary to replace Hashtable for multi-threaded object cache processing. When the problem can be solved smoothly, it is found that its access efficiency is also improved compared with the previous one.

 

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.