本文转载: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. Global中的事件执行顺序

    The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to ap ...

  2. php多线程thread开发与应用的例子

    Php多线程的使用,首先需要PHP5.3以上版本,并安装pthreads PHP扩展,可以使PHP真正的支持多线程,扩展如何安装请自行百度 PHP扩展下载:https://github.com/kra ...

  3. PHP basename() 函数

    定义和用法 basename() 函数返回路径中的文件名部分. 语法 basename(path,suffix) 参数 描述 path 必需.规定要检查的路径. suffix 可选.规定文件扩展名.如 ...

  4. 第二章 LM3S USB处理器

    2.1 LM3S处理器简介 Luminary Micr公司Stellaris所提供一系列的微控制器是首款基于Cortex-m3的控制器,它们为对成本尤其敏感的嵌入式微控制器应用方案带来了高性能的32位 ...

  5. 让动画不再僵硬:Facebook Rebound Android动画库介绍

    introduction official site:http://facebook.github.io/reboundgithub : https://github.com/facebook/reb ...

  6. 关于标准库中的ptr_fun/binary_function/bind1st/bind2nd

    http://www.cnblogs.com/shootingstars/archive/2008/11/14/860042.html 以前使用bind1st以及bind2nd很少,后来发现这两个函数 ...

  7. 【HDOJ】2054 A == B ?

    这道题目起初看,so easy.再看一下ac率,注意到没有说明变量类型.显然是一道字符串的题.需要考虑+/-符号位,+.1.-.1.00010.0.+0.-00.00等情况,同时数组开到100000以 ...

  8. BOM List demo

    select level level_id,        t.*   from (select msi1.segment1 farther_item,                msi1.inv ...

  9. Linux Kernel ‘/net/socket.c’本地信息泄露漏洞

    漏洞名称: Linux Kernel ‘/net/socket.c’本地信息泄露漏洞 CNNVD编号: CNNVD-201312-037 发布时间: 2013-12-04 更新时间: 2013-12- ...

  10. 【转】 如何查看linux版本 如何查看LINUX是多少位

    原文网址:http://blog.csdn.net/hongweigg/article/details/7192471 一.如何得知自己正在使用的linux是什么版本呢,下面的几种方法将给你带来答案! ...