我有一個IEnumerable實體,它擁有大約100萬條記錄。我想執行Parallel.ForEach來插入這些數據。任務並行庫拋出NullReferenceException與IEnumerable
這裏說的是類我有什麼: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'一個新的連接,你得到同樣的錯誤? – Balah
只有在堆棧跟蹤中帶':'的行的含義是什麼? –
@balah:我可以嘗試,但建議不使用Parallel.ForEach for DB。 – nimi