【发布时间】:2016-02-04 10:41:24
【问题描述】:
我有一个 IEnumerable 实体,它拥有大约 10 万条记录。我想执行 Parallel.ForEach 来插入这些数据。
说这里是我所拥有的类:Employee.cs
SqlConneciton conn = base.GetConnection();
conn.open();
IEnumerable<Employee> employeeList = GetListofEmployeesFromDB();
Parallel.ForEach(employeeList
, employee =>
{
employee.add(conn, sqlTransaction);
});
Empployee.cs
{
public void add(SqlConnection conn, SqlTransaction sqlTransaction)
{
using (SqlCommand insertCmd = new SqlCommand("EmployeeInsert", conn))
{
insertCmd.CommandType = CommandType.StoredProcedure;
insertCmd.Transaction = transaction;
insertCmd.Parameters["@Name"].Value = this.Name;
insertCmd.ExecuteNonQuery();
this.id = (int)insertCmd.Parameters["@Id"].Value;
}
}
}
随着数据的插入,我看到有一个NPE在:
this.id = (int)insertCmd.Parameters["@Id"].Value;
不确定我是否遗漏了什么。这是我看到的例外。
System.AggregateException was unhandled
Message=AggregateException_ctor_DefaultMessage
Source=System.Threading
StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource,TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEach[TSource](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 body)
:
:
:
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart(Object obj)
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=Jobvite.Library
StackTrace:
:
:
:
at System.Threading.Tasks.Parallel.<>c__DisplayClass32`2.<PartitionerForEachWorker>b__30()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass3.<ExecuteSelfReplicating>b__2(Object )
InnerException:
【问题讨论】:
-
出于好奇,如果您在
Employee.Add中使用新连接,您会收到同样的错误吗? -
stacktrace中只有
:的行是什么意思? -
@balah:我可以尝试,但建议不要将 Parallel.ForEach 用于 DB。
-
@henk:NPE 是空指针异常,我的错……是的,我没有意识到每个人都算数十万……更新它……
-
@alex:我删除了一些我不想粘贴到这里的代码。
标签: c# .net task-parallel-library parallel.foreach