3

我在 .Net 4.5 下运行以下代码

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 循环的每个实例上放置超时异常?

4

1 回答 1

3

As mentioned in the comments, you need to use thread local data tables, Parallel has built in support for that. Also there is no reason to use Parallel.For, ForEach would be much more appropriate for this situation.

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); 
                    }
                });
于 2013-10-11T16:54:21.560 回答