Parallel.Invoke and Index was outside the bounds of the array [duplicate]

Solution 1:

If you change something in threads, make sure that no one can do that at the same time. In your case it easy, just add lock on list.

private static void AddToResult(string reportName, IList data, string message, List<Recon> resultList)
{
    var recon = new Recon
    {
        ReportName = reportName,
        ExcelData = ExcelManager.GetExcelData(reportName, message, data)
    };

    lock (resultList)
    {
        resultList.Add(recon);
    }
}

Also ensure that your code do not change data list.

Solution 2:

The fundamental issue is that List<T>.Add is not thread safe. By trying to add to the same array in parallel, you are most likely causing an internal collision, potentially during resizing operations and it is leading to failed indexing.

The proper solution is to lock before adding:

private static object _locker = new object();

private static void AddToResult(string reportName, IList data, string message, List<Recon> resultList)
{
    var recon = new Recon
    {
        ReportName = reportName,
        ExcelData = ExcelManager.GetExcelData(reportName, message, data)
    };

    lock(_locker)
    {
        resultList.Add(recon);
    }
}