当我打电话给List<T>.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)
Run Code Online (Sandbox Code Playgroud)
我还看到Enumerable.Any针对同一列表抛出此异常。
这可能是由于竞争状况引起的。如果两个或多个线程同时修改列表,则列表可能会损坏。此后,以后对该列表进行的任何操作都将失败。
这是将重现它的示例。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,它可能发生在第一次迭代或数千次迭代之后。
| 归档时间: |
|
| 查看次数: |
3403 次 |
| 最近记录: |