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.
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);
}