【问题标题】:Why does List<T>.Add throw an index out of range exception? [duplicate]为什么 List<T>.Add 会抛出索引超出范围异常? [复制]
【发布时间】:2019-04-16 22:21:58
【问题描述】:

当我调用List&lt;T&gt;.Add(T) 时,它会抛出这个异常:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.List`1.Add(T item)
   at ConsoleApp5.Program.AddToList(Int32 seed) 

我还看到Enumerable.Any 针对同一个列表抛出了这个异常。

【问题讨论】:

标签: c# .net


【解决方案1】:

这可能是由竞争条件引起的。如果两个或更多线程同时修改列表,它可能会损坏。在那之后,以后对列表的任何操作都将失败。

这是一个可以重现它的示例。

    static List<int> TestList;
    const int ThreadCount = 10;
    const int IterationsA = 1000;

        static int count = 0;

    static void Main(string[] args)
    {
        try
        {
            while (true)
            {
                TestList = new List<int>();
                List<Thread> threads = new List<Thread>();

                for (var x = 0; x < ThreadCount; x++)
                {
                    var t = new Thread(() => AddToList(x));
                    t.Start();
                    threads.Add(t);
                }

                foreach (var t in threads)
                    t.Join();

                var b = TestList.Any(i => i == 1);

                Console.WriteLine("Pass " + DateTime.Now.ToString("hh:mm:ss.fff"));
                count += 1;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.WriteLine($"Failed after {count} attempts");
        }

        Console.ReadLine();

    }

    static void AddToList(int seed)
    {
        try
        {
            var random = new Random(seed);

            for (var x = 0; x < IterationsA; x++)

            {
                TestList.Add(random.Next());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.WriteLine($"Failed after {count} attempts");
            Console.ReadLine();
        }
    }

请注意,它可能发生在第一次迭代或数千次迭代之后。

【讨论】:

  • 你完全没有抓住重点。我写这篇文章是为了帮助那些在生产中看到这个异常并且不明白出了什么问题的人。如果他们已经知道存在竞争条件,他们就不会搜索这个问题。
  • 我明白了,但这个答案至少可以说明如何解决这个问题,否则这不是一个答案
  • 我写这篇文章是为了帮助那些在生产中看到这个异常但不明白出了什么问题的人或者他们可以找到this question,或其他一些类似的一个
  • 或者确实是IndexOutOfRangeException docs - "违反线程安全。如果对象不是以线程安全的方式访问,来自不同线程的诸如...之类的操作可能会抛出 IndexOutOfRangeException。此异常通常是间歇性的,因为它依赖于竞争条件。”
  • @stuartd,我的意思是,如果我们在这里告诉所有帖子“您应该检查文档”,那么根本就不会有任何问题。
猜你喜欢
  • 2016-07-01
  • 2016-05-05
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
相关资源
最近更新 更多