[C #] Thread Safe Dictionary in. NET 2.0

Source: Internet
Author: User

Using System. collections. generic; using System. threading; namespace CSharpUtilHelpV2 {// <summary> // based on. NET 2.0 for the Dictionary thread security operation tool class // description // default read lock timeout 1000 milliseconds // default write lock timeout 1000 milliseconds ///. NET 4.0 can be implemented using ConcurrentDictionary. /// </Summary> /// <typeparam name = "T"> generic </typeparam> public class ThreadSafeDictionaryV2 <T> {/* References * 1. * Synchronization Control Using Monitor or Mutex: Because the exclusive access model does not allow any form of concurrent access, this efficiency is always not very high. * In many cases, the application reads resources and writes less. To solve this problem, * C # provides the System. Threading. ReaderWriterLock class to adapt to Multi-User Read/single-user write scenarios. This class can implement the following functions: * If the resource is not locked by the write operation, any thread can lock the resource for read operations, and there is no limit on the number of read operation locks, that is, multiple threads can lock the read operation on the resource at the same time to read data. * If no read or write operation lock is added to a resource, one and only one thread can lock the resource by adding write operations to write data. In short, the read operation lock is a shared lock that allows multiple threads to read data at the same time. * The write operation lock is an exclusive lock that allows only one thread to perform write operations at the same time. * Reference link: http://www.csharpwin.com/dotnetspace/12761r5814.shtml ** 2. * ReaderWriterLock is used to synchronize access to resources. At any specific time, it allows multiple threads to simultaneously read or write data to a single thread. * When resources do not change frequently, ReaderWriterLock provides a higher throughput than simply allowing only one thread lock (such as Monitor) at a time. * ReaderWriterLock has the best performance when most access requests are read requests and the Write Access frequency is low and the duration is short. * Multiple read threads and a single write thread are operated in turn, so neither the read thread nor the write thread will be blocked for a long time. * Most methods to obtain a lock on ReaderWriterLock use a timeout value. Timeout can avoid deadlocks in applications. * If no timeout is used, the two threads will experience a deadlock. * Reference link: http://msdn.microsoft.com/zh-cn/library/system.threading.readerwriterlock (V = vs.80). aspx ** 3. Other links * http://tinythreadsafecache.codeplex.com/SourceControl/latest#TinyThreadSafeCache.cs * http://www.grumpydev.com/2010/02/25/thread-safe-dictionarytkeytvalue/ * http://stackoverflow.com/questions/157933/whats-the-best-way-of-implementing-a-thread-safe-dictionary * http://stackoverflow.com/questions/15095817/adding-to-a-generic-dictionary-causes-indexoutofrangeexception */ReaderWriterLock rwlock = new ReaderWriterLock (); // declare the read/write lock. NET 3.5 + ReaderWriterLockSlim Dictionary <string, T> dic = new Dictionary <string, T> (); // Dictionary static int readerTimeout = 1000; // by default, the read lock times out in 1000 milliseconds. static int writerTimeout = 1000; // default write lock timeout 1000 ms // <summary> // default constructor // </summary> public ThreadSafeDictionaryV2 () {}/// <summary> /// constructor with parameters /// </summary> /// <param name = "_ readerTimeout"> Read lock timeout setting (unit: milliseconds)] </param> /// <param name = "_ writerTimeout"> write lock timeout setting in milliseconds </param> public ThreadSafeDictionaryV2 (int _ readerTimeout, int _ writerTimeout) {readerTimeout = _ readerTimeout; writerTimeout = _ writerTimeout ;} /// <summary> // This [thread security] /// </summary> /// <param name = "key"> key </param> /// <returns> value </returns> public T this [string key] {get {rwlock. acquireReaderLock (readerTimeout); try {return dic [key];} finally {rwlock. releaseReaderLock () ;}} set {rwlock. acquireWriterLock (writerTimeout); try {dic [key] = value;} finally {rwlock. releaseWriterLock ();}}} /// <summary> /// Add [thread security] /// default timeout 1000 ms /// </summary> /// <param name = "key"> key </param> // <param name = "val"> value </param> public void Add (string key, T val) {Add (key, val, writerTimeout );} /// <summary> /// Add [thread security] /// </summary> /// <param name = "key"> key </param> /// <param name = "val"> value </param> /// <param name = "timeout"> timeout setting [ms] </param> public void Add (string key, T val, int timeout) {rwlock. acquireWriterLock (timeout); try {dic [key] = val;} finally {rwlock. releaseWriterLock ();}} /// <summary> /// Get [thread security] // The default timeout time is 1000 milliseconds /// </summary> /// <param name = "key"> key </param> // <returns> value </returns> public T Get (string key) {return Get (key, readerTimeout );} /// <summary> /// Get [thread security] /// </summary> /// <param name = "key"> key </param> /// <param name = "timeout"> timeout setting [ms] </param> // <returns> value </returns> public T Get (string key, int timeout) {rwlock. acquireReaderLock (timeout); try {T val; dic. tryGetValue (key, out val); return val;} finally {rwlock. releaseReaderLock ();}} /// <summary> /// Remove [thread security] // The default timeout time is 1000 milliseconds /// </summary> /// <param name = "key"> key </param> public void Remove (string key) {Remove (key, writerTimeout );} /// <summary> /// Remove [thread security] /// </summary> /// <param name = "key"> key </param> /// <param name = "timeout"> timeout setting [ms] </param> public void Remove (string key, int timeout) {rwlock. acquireWriterLock (timeout); try {dic. remove (key);} finally {rwlock. releaseWriterLock () ;}/// <summary> // Clear [thread security] /// default timeout 1000 ms // </summary> public void Clear () {Clear (writerTimeout );} /// <summary> /// Clear [thread security] /// </summary> /// <param name = "timeout"> time-out setting [millisecond] </param> public void Clear (int timeout) {rwlock. acquireWriterLock (timeout); try {dic. clear ();} finally {rwlock. releaseWriterLock ();}} /// <summary> /// ContainsKey [thread security] /// the default timeout value is 1000 milliseconds /// </summary> /// <param name = "key"> key </param> // <returns> whether to include </returns> public bool ContainsKey (string key) {return ContainsKey (key, readerTimeout );} /// <summary> /// ContainsKey [thread security] /// </summary> /// <param name = "key"> key </param> /// <param name = "timeout"> timeout setting [ms] </param> // <returns> whether to include </returns> public bool ContainsKey (string key, int timeout) {rwlock. acquireReaderLock (timeout); try {return dic. containsKey (key);} finally {rwlock. releaseReaderLock ();}} /// <summary> /// Count [thread security] /// default timeout 1000 milliseconds /// </summary> /// <returns> </returns> public int count () {return Count (readerTimeout );} /// <summary> // Count [thread security] /// </summary> /// <param name = "timeout"> time-out setting [millisecond] </param >/// <returns> Count </returns> public int Count (int timeout) {rwlock. acquireReaderLock (timeout); try {return dic. count;} finally {rwlock. releaseReaderLock ();}}}}

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.