TPL Parallel For Loop错误

问题描述 投票:2回答:2

我在parallel.for循环中遇到“发生一个或多个错误”异常:

at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken            cancellationToken)
at System.Threading.Tasks.Task.Wait()
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body)
at StaticClassLibrary.BLL.StaticClass.StatiMethod(String strExt, Object wTable, Object job, String BSPConnectionString) in c:\Users\FredWAD\Documents\Visual Studio 2010\Projects\PayrollCenterLibrary\BLL\ContributionFileManager.cs:line 218
   at myapp.staticlibrary.staticmethod(String str1, String str2) 

该应用程序采用结构集合,每个对象包含元数据,并将它们插入到数据库中。

违规代码如下:

Parallel.For(0, recordCnt, pOptions, d =>
               {
                   //flds = wTable.records[d].fields;
                   ssn = wTable.records[d].fields[fieldIndex].Value;
                   //rowId = wTable.records[d].fields[fieldIndex].rowId;
                   currentPerson = PersontManager.GetPerson(string1, string2);
                   hasContributions = WorkTableManager.RowHasContributionsNEW(List<string> lst, wTable.records[d]);
                   LoadRecordParallel(hasLoan, hasScratchpad, fieldIndex, wTable.records[d], object, string, string);
               }
           );

wTable =集合对象。

records =包含元数据的结构列表

fields =每条记录中的结构。每条记录都包含这些列表。

这本质上是一个表,包含行的结构(也包含有关每行的一些元数据)和单元格的结构。此错误似乎是随机发生的。我在这做错了什么?

c# multithreading task-parallel-library
2个回答
3
投票

您需要查看AggregateException上的InnerExceptions属性。这是TPL的默认行为,因为多个线程可能同时抛出异常。

有关更多信息,请参阅http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx

我的猜测是你有一些非线程安全的资源;当并行线程访问它时,资源会与另一个线程进入竞争状态,从而导致异常。第一个任务是找出并行查询的哪一行导致问题,进入该问题。如果数据库级别的行锁定不足,则可能与数据库有关。


0
投票

处理此问题的一种方法是在并行循环中放置一个try catch块。如果你可以在循环中处理异常,那么它不会与AggregateException爆发。

© www.soinside.com 2019 - 2024. All rights reserved.