本文转载: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. 如何从软硬件层面提升 Android 动画性能?

    若是有人问如何解决动画性能不佳的问题,Dan Lew Codes 总会反问:你是否使用了硬件层? 动画放映过程中每帧画面可能都要重绘.如果使用视图层,,渲染过的视图可以存入离屏缓存以待将来重用,而无需 ...

  2. 一位IT行业高收入者的理财规划方案

    一位IT行业高收入者的理财规划方案 http://zhuanlan.zhihu.com/invest/19670220 Alex · 12 天前 回望2013,这一年是极其不寻常的.理财浪潮席卷大江南 ...

  3. Vmware 8.00 文件共享ubuntu

    http://bolg.sinaapp.com/html/2012/1848.html 这是解决vm不能共享的解决方案. 今天学会的Linux命令: cp -i *** ~/tmp cd VMware ...

  4. php 使用jquery实现ajax

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  5. http://www.tuicool.com/articles/RzUzqei

    http://www.tuicool.com/articles/RzUzqei http://www.cnblogs.com/piaolingzxh/archive/2015/01/01/419783 ...

  6. .Net remoting, Webservice,WCF,Socket区别

    传统上,我们把计算机后台程序(Daemon)提供的功能,称为"服务"(service).比如,让一个杀毒软件在后台运行,它会自动监控系统,那么这种自动监控就是一个"服务& ...

  7. Android进阶篇-时间滑动控件

    仿Iphone时间选择滑动控件: WheelView.java: /** * @author Administrator * * 时间滑动滚轮 */ public class WheelView ex ...

  8. IP隧道基础研究

    static char banner[] __initdata = KERN_INFO "IPv4 over IPv4 tunneling driver\n"; static st ...

  9. IPv6 tutorial – Part 5: Address types and global unicast addresses

    https://4sysops.com/archives/ipv6-tutorial-part-5-address-types-and-global-unicast-addresses/ In my ...

  10. Cannot Create Supplier Site (Address) (文档 ID 1069032.1)

    Error Address and Site Creation - Unable to create address and sites because of the following error ...