zoukankan      html  css  js  c++  java
  • Dictionary在多线程情况下

    Add时出错

    错误信息:
    Index was outside the bounds of the array.
    详细信息:
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
    at ****.GetEnumDescription(Enum value)
    at ****.Page_Load(Object sender, EventArgs e)
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
    

    出错的地方应该就是enumCache.Add(value, str);这句了。

    但是左看右看,我也没看出这句有什么问题。这个方法里通过反射的方法将Enum里的Description元数据取出返回,但是由于反射是一个比较耗时的操作,所以这里用了一个Dictionary的对象将数据做了缓存。如果缓存里有就直接取缓存里的数据,如果没有再用常规方法获取。 www.it165.net

    毫无头绪啊。

    在Google上搜了一通,渐渐把问题聚焦在Dictionary.Insert方法里了,到MSDN里一查,果不其然是有问题的:

    1.A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
    2. 
    3.For a thread-safe alternative, see ConcurrentDictionary.

    长期以来虽然知道Dictionary、List的实例是对象来着,但是用的时候都是当作值类型来用的,也从来没有考虑过在多线程环境下会有什么样的情况。但是这样就引来了一个问题,为什么多线程同时操作Dictionary对象的时候会出错呢?

    其实我们平时使用Dictionary无非就用Add、Remove这样的方法,根本没有考虑过内部实现的机制。在Dictionary内部为了维 护Dictionary的功能和高效的特性,有自己的一些计数器和状态维护机制。Dictionary.Add方法实际上里头只有一句 话:this.Insert(key, value, true);也就是最终的实现都是在Insert方法里的。再用Reflector扒开Insert方法里的内容看看:

    
    
    01.private void Insert(TKey key, TValue value, bool add)
    02.{
    03.int freeList;
    04.if (key == null)
    05.{
    06.ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    07.}
    08.if (this.buckets == null)
    09.{
    10.this.Initialize(0);
    11.}
    12.int num = this.comparer.GetHashCode(key) & 0x7fffffff;
    13.int index = num % this.buckets.Length;
    14.for (int i = this.buckets[index]; i >= 0; i = this.entries[i].next)
    15.{
    16.if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
    17.{
    18.if (add)
    19.{
    20.ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    21.}
    22.this.entries[i].value = value;
    23.this.version++;
    24.return;
    25.}
    26.}
    27.if (this.freeCount > 0)
    28.{
    29.freeList = this.freeList;
    30.this.freeList = this.entries[freeList].next;
    31.this.freeCount--;
    32.}
    33.else
    34.{
    35.if (this.count == this.entries.Length)
    36.{
    37.this.Resize();
    38.index = num % this.buckets.Length;
    39.}
    40.freeList = this.count;
    41.this.count++;
    42.}
    43.this.entries[freeList].hashCode = num;
    44.this.entries[freeList].next = this.buckets[index];
    45.this.entries[freeList].key = key;
    46.this.entries[freeList].value = value;
    47.this.buckets[index] = freeList;
    48.this.version++;
    49.}

    在这里可以看到有大量的计数器存在,而我们再来倒回头看看最开始抛出的异常对象:IndexOutOfRangeException,如果计数器出错,相当有可能在使用计数器做下标时出现下标越界的情况。那么这是.Net的Bug么?

    在上面引用MSDN的时候微软已经明确说了,在多线程访问的时候不要使用Dictionary而应该使用ConCurrentDictionay,利用ConCurrentDictionay里的TryAdd、TryUpdate方法来避免出现类似的错误。

    其实多线程并发计算的时候,经常会出现计数错误的情况。

    举个例子,有这样一段程序:

    
    
    01.int i = 0;
    02.new Thread(() =>
    03.{
    04.for (int k = 0; k < 10; k++)
    05.{
    06.i++;
    07.}
    08.}).Start();
    09. 
    10.new Thread(() =>
    11.{
    12.for (int k = 0; k < 10; k++)
    13.{
    14.i++;
    15.}
    16.}).Start();


     

    按正常情况来看,在这两个线程都执行完以后,i的值应该都是20,但是现实情况却是有一定概率i值会不等于20。
    i++在执行的时候,CPU会得到类似这样的指令:
    A: 表示这段指令是A线程上的,B: 表示这段指令是B线程上的

    
    
    1.A: mov eax,[x]
    2.A: inc eax
    3.A: mov [x],eax

    如果是在一个线程里顺序执行两次i++,那么执行的时候CPU得到的指令应该是这样的:

    
    
    1.A: mov eax,[x]
    2.A: inc eax
    3.A: mov [x],eax
    4.A: mov eax,[x]
    5.A: inc eax
    6.A: mov [x],eax

    但是在两个线程中分别执行i++,情况就会变得非常复杂,CPU可能得到这样的指令:

    
    
    1.A: mov eax,[x]
    2.B: mov eax,[x]
    3.A: inc eax
    4.B: inc eax
    5.A: mov [x],eax
    6.B: mov [x],eax

    假如在执行前x里的值是0,那么执行完以后线程A里的x的值变成了1,线程B里x的值也变成了1。也就是说,线程A和线程B里分别执行完i++以后,i实际上只增加了1(两个线程的eax是独立的)。

    在分析完了原因以后,大致就可以知道如何解决这种问题了。

    1. 使用线程锁,在读写对象时将对象锁定直至操作结束(Link);
    2. 使用线程安全的ConcurrentDictionary对象,并使用TryAdd或TryUpdate方法操作(Link);
    3. 丢弃原有的Dictionary对象,重新创建一个新的对象,然后由GC将原先有错误的Dictionary对象回收。

    经过昨天这个事情以后再也不能对线程掉以轻心。线程是好用,但是要用好还是要花费一番心思的。

  • 相关阅读:
    数据库(SQL Server)管理数据库表~新奇之处
    疯狂C#~伴随着我的库存管理¥
    书中的银行,我们一起奋斗的C#,只因乐在其中~
    MyBatis的经典案例
    Spring MVC的配置文件(XML)的几个经典案列
    Spring MVC注解的一些案列
    WebService的一些案例
    AOP面向切面编程的四种实现
    Struts 2的OGNL的根对象
    Struts 2的拦截器(Interceptor)总结
  • 原文地址:https://www.cnblogs.com/qook/p/4848516.html
Copyright © 2011-2022 走看看