Using the Concurrentdictionary multithreaded synchronization dictionary Collection instance

Source: Internet
Author: User
Tags tojson
In the previous period, most of my base class use lock and Hashtable combination to implement multi-thread cache conflict processing, but sometimes use these two collocation is not satisfactory, occasionally there is a collection has been added to the exception, the code to do multi-party processing after the same, and finally adopted the. NET 4.0 after the introduction of the Concurrentdictionary multi-Threaded synchronization dictionary collection, the problem solved successfully.

1, using lock and Hashtable combination to achieve

In my base class, build business objects, generally with bllfactory<t>. Instance will be able to get the application of the corresponding business object.

var result = Bllfactory<customer>. Instance.findfirst (); Console.WriteLine (Result. ToJson ());

so use Bllfactory<t>. Instance this build object, put them into the Hashtable, because of the need to design multi-threaded conflict processing, so you need to use the lock object to implement locking processing.

Hashtable represents a collection of key/value pairs. In the. NET Framework, Hashtable is a container provided by the System.Collections namespace that handles and behaves like Key-value key-value pairs, where key is usually used for quick lookups, and key is case-sensitive; value is used to store the value corresponding to key. Key-value Key-value pairs in Hashtable are all object types, so hashtable can support any type of KeyValue key-value pair, and any non-null object can be used as a key or a value.

In this way, occasionally on the web side, or there is a multi-threaded access violation problem, for this we can also use multithreaded test code to test reproduce the error,

            try{                list<thread> List = new list<thread> (); for (int i = 0; i <; 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 trace code gets the error message as shown below.

Therefore, you can see from the above code that using lock (syncRoot) does not occur with multithreaded conflict issues.

2. Replace Hashtable with Concurrentdictionary

Concurrentdictionary is a. net4.0 launched a set of thread-safe one of the set, and it was released along with Concurrentstack,concurrentqueue and other types, their single-threaded version (thread insecure, Queue,stack,dictionary) We must not be strangers. concurrentdictionary<TKey, tvalue> can be accessed by multiple threads at the same time, and thread-safe, usage is much the same as dictionary, but with a few more methods. Concurrentdictionary belongs to the System.Collections.Concurrent namespace.

The System.Collections.Concurrent namespace provides multiple thread-safe collection classes. When multiple threads concurrently access the collection, these classes should be used in place of the corresponding types in the System.Collections and System.Collections.Generic namespaces .

Concurrentdictionary This class provides the following methods for handling the collection

public bool TryAdd (TKey key, TValue value) publicly bool Tryupdate (TKey key, TValue newvalue, TValue comparisonvalue) public T Value 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& Gt valuefactory)

Using Concurrentdictionary instead of Hashtable, let's take a look at the implementation code for the Bllfactory class as shown below.

    <summary>///the factory class that constructs the business class///</summary>///<typeparam name= "T" > Business object Type </typeparam>public The class bllfactory<t> where t:class{//is cached using Concurrentdictionary thread-safe collection classes instead of Hashtableprivate static concurrentdictionary<string, object> concurrentcache = new concurrentdictionary<string, object> (); <summary>///Create or get an 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); Reflection created, and cached return BLL;}                );}}    

We can see that the code is much simplified, and using the previous multithreaded test code, we get the data smoothly, without any exception.

Running code can be implemented smoothly without the multithreading access exception that occurred before using Hashtable.

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.