本文转载:http://www.cnblogs.com/kiddo/archive/2008/09/25/1299089.html

我们说一个数据结构是线程安全指的是同一时间只有一个线程可以改写它。这样即使多个线程来访问它,它也不会产生对线程来说很意外的数据。
C#中的Dictionary不是线程安全的,我在下面这个例子中,把一个Dictionary对象作为了全局的static变量。会有多个线程来访问它。所以我需要包装一下.net自带的Dictionrary.
发生冲突的部分无非是写的地方,所以在离写Dictionary最近的地方加一个锁。其他的外层代码可以自带的Dictionary相同了。
我们看Dictionary的实现接口,
 
自定义一个线程安全的数据对象类。
   public class SafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly object syncRoot = new object();
private readonly Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); #region IDictionary<TKey,TValue> Members /// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</exception>
/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
public void Add(TKey key, TValue value)
{
lock (syncRoot)
{
d.Add(key, value);
}
} /// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
public bool ContainsKey(TKey key)
{
return d.ContainsKey(key);
} /// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
/// </summary>
/// <value></value>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</returns>
public ICollection<TKey> Keys
{
get
{
lock (syncRoot)
{
return d.Keys;
}
}
} /// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception>
/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
public bool Remove(TKey key)
{
lock (syncRoot)
{
return d.Remove(key);
}
} /// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGetValue(TKey key, out TValue value)
{
lock (syncRoot)
{
return d.TryGetValue(key, out value);
}
} /// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
/// </summary>
/// <value></value>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</returns>
public ICollection<TValue> Values
{
get
{
lock (syncRoot)
{
return d.Values;
}
}
} /// <summary>
/// Gets or sets the <see cref="TValue"/> with the specified key.
/// </summary>
/// <value></value>
public TValue this[TKey key]
{
get { return d[key]; }
set
{
lock (syncRoot)
{ d[key] = value;
}
}
} /// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception>
public void Add(KeyValuePair<TKey, TValue> item)
{
lock (syncRoot)
{
((ICollection<KeyValuePair<TKey, TValue>>)d).Add(item);
}
} /// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only. </exception>
public void Clear()
{
lock (syncRoot)
{
d.Clear();
}
} /// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <returns>
/// true if item is found in the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)d).Contains(item);
} /// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">arrayIndex is less than 0.</exception>
/// <exception cref="T:System.ArgumentNullException">array is null.</exception>
/// <exception cref="T:System.ArgumentException">array is multidimensional.-or-arrayIndex is equal to or greater than the length of array.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"></see> is greater than the available space from arrayIndex to the end of the destination array.-or-Type T cannot be cast automatically to the type of the destination array.</exception>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
lock (syncRoot)
{
((ICollection<KeyValuePair<TKey, TValue>>)d).CopyTo(array, arrayIndex);
}
} /// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <value></value>
/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</returns>
public int Count
{
get { return d.Count; }
} /// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get { return false; }
} /// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <returns>
/// true if item was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false. This method also returns false if item is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
lock (syncRoot)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)d).Remove(item);
}
} /// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return ((ICollection<KeyValuePair<TKey, TValue>>)d).GetEnumerator();
} /// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)d).GetEnumerator();
} #endregion
}

  

 
微软4.0框架已经有了这个线程安全的Dictionary。
ConcurrentDictionary<TKey, TValue> 类
详细可以查看:http://msdn.microsoft.com/zh-cn/library/dd287191(v=vs.110).aspx
 
4.0中新增的线程安全集合类:
 
线程安全集合类 非线程安全集合类

ConcurrentQueue<T>

Queue<T>

ConcurrentStack<T>

Stack<T>

ConcurrentBag<T>

List<T>

ConcurrentDictionary<TKey,TValue>

Dictionary<TKey,TValue>

自定义Dictionary支持线程安全的更多相关文章

  1. 再记一次w3wp占用CPU过高的解决过程(Dictionary和线程安全)

    在此之前项目有发生过两次类似的状况,都得以解决,但最近又会发现偶尔CPU会跑满,虽然之前使用过WinDbg解决过两次问题但人的记忆是不可靠的,今天处理同样问题的时候还是遇到了一些障碍,这一次希望可以记 ...

  2. Shiro第二篇【介绍Shiro、认证流程、自定义realm、自定义realm支持md5】

    什么是Shiro shiro是apache的一个开源框架,是一个权限管理的框架,实现 用户认证.用户授权. spring中有spring security (原名Acegi),是一个权限框架,它和sp ...

  3. shiro自定义realm支持MD5算法认证(六)

    1.1     散列算法 通常需要对密码 进行散列,常用的有md5.sha, 对md5密码,如果知道散列后的值可以通过穷举算法,得到md5密码对应的明文. 建议对md5进行散列时加salt(盐),进行 ...

  4. 自定义ScrollView 支持添加头部

    自定义ScrollView 支持添加头部并且对头部ImageView支持放大缩小,上滑头部缩小,下滑头部显示放大 使用方式: scrollView = (MyScrollView) findViewB ...

  5. 牛客网Java刷题知识点之为什么HashMap不支持线程的同步,不是线程安全的?如何实现HashMap的同步?

    不多说,直接上干货! 这篇我是从整体出发去写的. 牛客网Java刷题知识点之Java 集合框架的构成.集合框架中的迭代器Iterator.集合框架中的集合接口Collection(List和Set). ...

  6. Dictionary(支持 XML 序列化),注意C#中原生的Dictionary类是无法进行Xml序列化的

    /// <summary> /// Dictionary(支持 XML 序列化) /// </summary> /// <typeparam name="TKe ...

  7. Http请求封装(对HttpClient类的进一步封装,使之调用更方便。另外,此类管理唯一的HttpClient对象,支持线程池调用,效率更高)

    package com.ad.ssp.engine.common; import java.io.IOException; import java.util.ArrayList; import jav ...

  8. 自定义 ThreadPoolExecutor 处理线程运行时异常

    自定义 ThreadPoolExecutor 处理线程运行时异常 最近看完了ElasticSearch线程池模块的源码,感触颇深,然后也自不量力地借鉴ES的 EsThreadPoolExecutor ...

  9. spring boot使用自定义配置的线程池执行Async异步任务

    一.增加配置属性类 package com.chhliu.springboot.async.configuration; import org.springframework.boot.context ...

随机推荐

  1. Python中文全攻略

    原文链接:http://blog.csdn.net/mayflowers/archive/2007/04/18/1568852.aspx 1.        在Python中使用中文 在Python中 ...

  2. iOS开发UI篇—UITabBarController生命周期(使用storyoard搭建)

    iOS开发UI篇—UITabBarController生命周期(使用storyoard搭建)   一.UITabBarController在storyoard中得搭建 1.新建一个项目,把storyb ...

  3. SQLite入门与分析(八)---存储模型(3)

    写在前面:接上一节,本节主要讨论索引页面格式,以及索引与查询优化的关系. (1)索引页面格式sqlite> select * from sqlite_master;table|episodes| ...

  4. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)

    一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied ...

  5. JAVA实现word doc docx pdf excel的在线浏览 - 仿百度文库 源码

    我们具体实现思路是这样的 首先下载并安装openoffice和swftools openoffice下载地址:http://www.openoffice.org/download/index.html ...

  6. (?m)

    centos6.5:/root/sbin#cat -n vv 1 192.168.11.186,192.168.11.187 35199,3306 Dec 7, 2016 11:40:02.75052 ...

  7. WCF - Developers Tools

    For developing a WCF service application, there are mainly two tools – Microsoft Visual Studio and C ...

  8. INCOIN Importing Multilingual Items (Doc ID 278126.1)

    APPLIES TO: Oracle Inventory Management - Version: 11.5.9 to 11.5.10.CU2 - Release: 11.5 to 11.5 GOA ...

  9. nginx 安全漏洞 (CVE-2013-4547)

    Nginx 的安全限制可能会被某些请求给忽略,(CVE-2013-4547). 当我们通过例如下列方式进行 URL 访问限制的时候,如果攻击者使用一些没经过转义的空格字符(无效的 HTTP 协议,但从 ...

  10. 调试UnhandledExceptionFilter

    kernel32!UnhandledExceptionFilter通过判断当前进程是否附加了调试器,如果附加,就把异常交给调试器,如果没有,就把异常交给进程的UnhandledExceptionFil ...