Under what circumstance System.Collections.ArrayList.Add throws IndexOutOfRangeException?

后端 未结 3 1756
梦谈多话
梦谈多话 2020-12-06 00:50

We are experiencing weird bug at production environment we cannot debug nor inject logging code. I am trying to figure this up but following stack trace confuse me.

3条回答
  •  误落风尘
    2020-12-06 01:10

    It boils down to List not being thread safe. I have had IndexOutOfRangeException occuring when iterating over a list after adding items using multiple threads without synchronization. The code below could corrupt the items count and result in IndexOutOfRangeException while iterating the list subsequently,

    List updatedFills = new List();
    Parallel.ForEach (trades, (trade) =>
    {
        TradeFillInfo fill = new TradeFillInfo();
    
        //do something
    
        updatedFills.Add(fill); //NOTE:Adding items without synchronization
    });
    
    foreach (var fill in updatedFills) //IndexOutOfRangeException here sometimes
    {
        //do something
    }
    

    Synchronizing the Add() with a lock statement will fix the issue.

    lock (updatedFills)
    {
        updatedFills.Add(fill);
    }
    

提交回复
热议问题