C# 并行调试失控线程。For循环
我在.NET4.5下运行了以下代码C# 并行调试失控线程。For循环,c#,multithreading,task-parallel-library,C#,Multithreading,Task Parallel Library,我在.NET4.5下运行了以下代码 Parallel.For(0, fileArray.Length, i => { DataRow dataRow = table.NewRow(); var dr = GetDataRow(fileArray[i], dataRow, parameters); if (dr["MyVariable"].ToString() != "0"
Parallel.For(0, fileArray.Length, i =>
{
DataRow dataRow = table.NewRow();
var dr = GetDataRow(fileArray[i], dataRow, parameters);
if (dr["MyVariable"].ToString() != "0")
{
try
{
table.Rows.Add(dr);
}
catch (Exception exception)
{
ConfigLogger.Instance.LogError(exception);
}
}
}
);
这个循环看起来是随机的,它会使机器上的处理器达到最大值,并使循环停止前进。这是在处理11k文件,我无法使用较小的一组文件重复它。有没有人对如何调试这个问题有什么想法,并找出是什么原因造成的?我无法让它在我的机器上复制,我的机器和生产之间的区别如下
生产Win 7 64位.Net 4.5
Win 8 64位.Net 4.5.1的开发
是否有方法在parallel.for循环的每个实例上放置超时异常?如注释中所述,您需要使用线程本地数据表,
parallel
内置了对此的支持。此外,没有理由使用并行。对于
,ForEach
更适合这种情况
Parallel.ForEach(fileArray,
() =>
{
lock(table)
{
//Create a temp table per thread that has the same schema as the main table
return table.Clone();
}
},
(file, loopState, localTable) =>
{
DataRow dataRow = localTable.NewRow();
var dr = GetDataRow(file, dataRow, parameters);
if (dr["MyVariable"].ToString() != "0")
{
try
{
localTable.Rows.Add(dr);
}
catch (Exception exception)
{
ConfigLogger.Instance.LogError(exception);
}
}
return localTable;
},
(localTable) =>
{
lock (table)
{
//Merge in the thread local table to the master table
table.Merge(localTable);
}
});
可能GetDataRow需要很多时间,因为此循环中的任何其他内容都不可能。您是否尝试使用相同的数据进行复制?GetDataRow()是处理数据的工具,是我编写的一个函数。通常需要一到两秒钟的时间…偶尔,在没有任何解释的情况下,循环会被卡住。我还没有找到一种方法来找出什么文件或者为什么它会被卡住。你有没有尝试用相同的数据复制?也许这个过程需要异常长的时间。循环没有被卡住,循环中的代码被卡住。我使用完全相同的数据集…并在本地运行多次。你很可能是对的……但是我没有办法知道是什么导致了看似“无限”的循环,也就是说,处理器被锁定了10分钟而进度条没有移动。该过程通常总共需要5分钟。p、 这只在生产机器上每隔5-10次发生一次,并且在常规for循环中不会发生。
table。NewRow
和table。Rows
不是线程安全的。是否存在其他不安全操作?这些bug至少必须被修复,但它们也可能会导致奇怪的行为。这非常有效,并允许我去除一些其他的问题,我现在认为这些问题是由于缺乏线程安全性而产生的。