【发布时间】:2016-04-01 08:08:44
【问题描述】:
我使用了很多 parallel foreach 循环。它们主要用于详细说明数据并将它们添加到列表中。
这是我的方法的一个例子:
System.Threading.Tasks.Parallel.ForEach(magazzini, m =>
{
try
{
warehouse.Add(new WAREHOUSE()
{
ID = m.Id,
NAME = m.new_name,
CODE = m.new_codice,
INTEGRATION_KEY = m.dynamics_integrationkey,
RESOURCE_ID = m.new_mobileuser == null ? Guid.Empty : m.new_mobileuser.Id
});
}
catch (Exception ex)
{
Logging.Error(authToken, string.Format("GetAllMagazzini|Magazzini|{0}", ex.InnerException));
}
});
我在this old post 中读到它可能是由List<T> 的非线程安全属性引起的。我的问题如下:
我不仅有像这样的 for 循环,而且还有包含大量操作的长循环。我不得不使用parallel.foreach,因为使用经典的foreach 会使查询超时,因为它位于WebService 上。
如何使用parallel.foreach 避免indexOutOfBoundException?我必须将List<T> 更改为其他内容?
【问题讨论】:
标签: c# multithreading foreach parallel-processing indexoutofboundsexception