【问题标题】:Getting Collection was modified; enumeration operation may not execute. exception获取收藏已修改;枚举操作可能无法执行。例外
【发布时间】:2014-01-10 04:17:30
【问题描述】:

获取收藏已修改;枚举操作可能无法执行。异常

代码:

public static string GetValue(List<StateBag> stateBagList, string name)
{
    string retValue = string.Empty;

    if (stateBagList != null)
    {
        foreach (StateBag stateBag in stateBagList)
        {
            if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
            {
                retValue = stateBag.Value;
            }
        }
    }

    return retValue;
}

有时不是每次都在这个地方得到这个异常。

堆栈跟踪:

在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource 资源)

在 System.Collections.Generic.List`1.Enumerator.MoveNextRare()

在 System.Collections.Generic.List`1.Enumerator.MoveNext()

在 Tavisca.TravelNxt.Shared.Entities.StateBag.GetValue(List`1 stateBagList, String name)


@没有人尝试过以下代码,但仍然出现异常

代码:

 class StateBag
{
    public string Name;
    public string Value;
}

class Program
{
    static List<StateBag> _concurrent = new List<StateBag>();

    static void Main()
    {
        var sw = new Stopwatch();
        try
        {
            sw.Start();
            Thread thread1 = new Thread(new ThreadStart(A));
            Thread thread2 = new Thread(new ThreadStart(B));
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();
            sw.Stop();
        }
        catch (Exception ex)
        {
        }


        Console.WriteLine("Average: {0}", sw.ElapsedTicks);
        Console.ReadKey();
    }

    private static Object thisLock = new Object();

    public static string GetValue(List<StateBag> stateBagList, string name)
    {
        string retValue = string.Empty;


        if (stateBagList != null)
        {
            lock (thisLock)
            {
                foreach (StateBag stateBag in stateBagList)
                {
                    if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        retValue = stateBag.Value;
                    }
                }
            }

        }



        return retValue;
    }

    static void A()
    {
        for (int i = 0; i < 5000; i++)
        {
            _concurrent.Add(new StateBag() { Name = "name" + i, Value = i.ToString() });
        }
    }

    static void B()
    {
        for (int i = 0; i < 5000; i++)
        {
            var t = GetValue(_concurrent, "name" + i);
        }
    }
}

【问题讨论】:

  • 传递给此方法的 stateBagList 可能会在其他地方更改。
  • 我猜这个方法可能是从 1 个线程调用的,而 List 正在同时从另一个线程被修改。
  • 我建议您只对 stateBagList 使用 ConcurrentDictionary,并将其从名称中删除(如果它是唯一的)。这将比串行搜索列表更高效,并且无需您自己的锁定逻辑。

标签: c#


【解决方案1】:

获取收藏已修改;枚举操作可能无法执行。异常

原因:当您正在循环的枚举在同一个线程或其他线程中被修改时,会发生此异常。

现在,在您提供的代码中不存在任何此类情况。这意味着您可能在多线程环境中调用它,并且集合在其他线程中被修改。

解决方案: 对您的枚举实施锁定,以便一次只有一个线程可以访问。应该这样做。

private static Object thisLock = new Object();
public static string GetValue(List<StateBag> stateBagList, string name)
{
    string retValue = string.Empty;

    if (stateBagList != null)
    {
        lock(thisLock)
        {
            foreach (StateBag stateBag in stateBagList)
            {
               if (stateBag.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
               {
                retValue = stateBag.Value;
                }
             }
        }
    }

    return retValue;
}

【讨论】:

  • 是的,它在覆盖线程环境中运行,但通过添加锁定枚举可能会减慢我的应用程序
  • @PravinBakare 看到我更新的答案。但它会运行,我想慢一点总比不运行好
  • @NoOne 将 thisLock 更改为静态。
【解决方案2】:

虽然锁定是修复原始实现的正确方法,但可能有更好的方法,它会涉及更少的代码和潜在的错误。

以下演示控制台应用使用 ConcurrentDictionary 而不是 List,并且是完全线程安全的,无需您自己的锁定逻辑。

它还提供更好的性能,因为字典查找比串行搜索列表要快得多:

class StateBag
{
    public string Name;
    public string Value;
}

class Program
{
    public static string GetValue(ConcurrentDictionary<string, StateBag> stateBagDict, string name)
    {
        StateBag match;
        return stateBagDict.TryGetValue(name.ToUpperInvariant(), out match) ? 
            match.Value : string.Empty;
    }

    static void Main(string[] args)
    {
        var stateBagDict = new ConcurrentDictionary<string, StateBag>();

        var stateBag1 = new StateBag { Name = "Test1", Value = "Value1" };
        var stateBag2 = new StateBag { Name = "Test2", Value = "Value2" };

        stateBagDict[stateBag1.Name.ToUpperInvariant()] = stateBag1;
        stateBagDict[stateBag2.Name.ToUpperInvariant()] = stateBag2;

        var result = GetValue(stateBagDict, "test1");

        Console.WriteLine(result);
    }
}

【讨论】:

    【解决方案3】:

    这是因为您的应用程序中的其他线程正在修改 stateBagList。您可以做两件事...在引用 stateBagList 的代码块周围使用锁定,或者您可以在 GetValues 方法中制作 stateBagList 的深层副本,然后在 for 循环中使用新列表。

    【讨论】:

      【解决方案4】:

      如前所述,您需要在枚举周围加一个锁。

      但是,该操作仅在您还锁定正在修改集合的语句时才有效。

      static void A()
      {
          for (int i = 0; i < 5000; i++)
          {
              lock(thisLock) 
              {
                  _concurrent.Add(new StateBag() { Name = "name" + i, Value = i.ToString() });
              }
          }
      }
      

      否则,您所做的只是确保一次只有一个线程可以枚举集合。在进行此单个枚举时,单个线程或多个其他线程仍可能正在修改集合。

      我还推荐以下链接: http://www.albahari.com/threading/part2.aspx#_Thread_Safety_and_NET_Framework_Types

      其他提示: 可以像这样锁定集合本身:

      lock(_concurrent) { //statements}
      

      GetValue 方法可以这样简化:

      public static string GetValue(List<StateBag> stateBagList, string name)
      {
          if (stateBagList != null)
          {
              lock (thisLock)
              {
                  return stateBagList.FirstOrDefault
                       (x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
                  }
              }
          }    
      
          return string.Empty;
      }
      

      【讨论】:

        【解决方案5】:

        将List 替换为SynchronizedCollection。它是线程安全的集合类。

        它通过锁定来实现这一点,因此您基本上拥有一个List,其中每个访问都包含在一个锁定语句中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-01
          相关资源
          最近更新 更多