Parallel.Foreach 给出错误“索引超出了数组的范围”
Posted
技术标签:
【中文标题】Parallel.Foreach 给出错误“索引超出了数组的范围”【英文标题】:Parallel.Foreach giving error " Index was outside the bounds of the array " 【发布时间】:2013-12-13 07:09:55 【问题描述】:我在 parallel.foreach 中遇到了一些问题,即“索引超出了数组的范围”。我正在为 parallel.foreach 附加一些代码以及它崩溃的地方。
var lstFRItems = session.CreateCriteria<TFRItem>().Add(Restrictions.Eq("TSCEnterprise.FEnterpriseID", EnterpriseId)).AddOrder(Order.Asc("FName")).List<TFRItem>();
List<FRItemAccount> lstItemAccount = new List<FRItemAccount>();
var ListAccounts = session.CreateCriteria<TFRItemAccount>().List<TFRItemAccount>(); //lstFRItems.Select(i => new i.TFRItemAccounts ).ToList();
//foreach (var item in lstFRItems)
Parallel.ForEach(lstFRItems, item =>
var lstItemAcc = ListAccounts.Where(i => i.TFRItem == item); //item.TFRItemAccounts.ToList();
FRItemAccount account = new FRItemAccount();
account.ItemID = item.FItemID;
account.ItemAccount = new List<ItemAccount>();
// foreach (var itemAcct in lstItemAcc)
Parallel.ForEach(lstItemAcc, itemAcct =>
ItemAccount oItemAccount = new ItemAccount();
if (itemAcct != null)
oItemAccount.ItemAccountID = itemAcct.FItemAccountID;
if (itemAcct.TSCProperty == null)
oItemAccount.ForID = itemAcct.TSCCompany.FCompanyID;
oItemAccount.ForCompanyName = "Co# " + "- " + itemAcct.TSCCompany.FID + " " + itemAcct.TSCCompany.FName;
oItemAccount.FID = itemAcct.TSCCompany.FID;
oItemAccount.ForType = 1;
else
oItemAccount.ForID = itemAcct.TSCProperty.FPropertyID;
oItemAccount.ForCompanyName = "Prop# " + "- " + itemAcct.TSCProperty.FID + " " + itemAcct.TSCProperty.FName;
oItemAccount.FID = itemAcct.TSCProperty.FID;
oItemAccount.ForType = 2;
oItemAccount.Account = itemAcct.FAccount;
account.GLAccount = itemAcct.FAccount.ToString("#0.000"); //Formatted by Lhore Bansal
// account.Account = itemAcct.FAccount;
oItemAccount.isExisting = true;
//Original TFRItemAccount
oItemAccount.orgItemAccount = itemAcct;
if (lstItemAcc == null)
account.ItemID = item.FItemID;
account.ItemAccount.Add(oItemAccount);
);
//Original tFRItem
account.Item = item;
//account.BaseAccount = Convert.ToDouble(item.FBaseAccount.ToString("F0")); // commented by jeet
account.BaseAccount = Convert.ToDouble((int)item.FBaseAccount); // added by jeet
account.Name = item.FName;
account.Type = item.FType;
lstItemAccount.Add(account);
);
// tx.Commit();
return Item = lstItemAccount;
它在倒数第三行“lstItemAccount.Add(account)”处崩溃。当我在 lstItemAccount 中看到时,它有一些计数,并且在基础部分它有一个错误 "base System.SystemException = "Source array was not long enough. Check srcIndex and length, and the array's lower bounds."".
这个错误的解决方法是什么?
【问题讨论】:
仅供参考 - 您可能遇到lstItemAccount
的线程问题。
你得到这个问题的有效答案了吗?
【参考方案1】:
我会使用ConcurrentBag<T>
而不是List<T>
。 List<T>
是专为一个线程的访问而设计的。
【讨论】:
【参考方案2】:这有关系
ListAccounts.Where(i => i.TFRItem == item);
account.ItemAccount.Add(oItemAccount);
lstItemAccount.Add(account);
列表和数组不是线程安全的。请改用ConcurrentBag
【讨论】:
以上是关于Parallel.Foreach 给出错误“索引超出了数组的范围”的主要内容,如果未能解决你的问题,请参考以下文章