I have a method which will insert a list of id's in to the Database. I have used Parallel.ForEach to speed up the process but it's inserting one record into Databse and generating object reference not set to instance of object for the rest of the Records but the same works with foreach loop.
Here is my method.
[HttpPost]
public JsonResult MoveIds(List<long> Ids, int DestId)
{
var sb = new StringBuilder();
var failedIds = new List<long>();
var requestNumber = 1;
Parallel.ForEach(Ids, Id =>
{
try
{
//Code to insert id into Database
//returns HasErrors if there are any errors while inserting
// and error message
lock (sb)
{
if (HasErrors)
{
sb.AppendLine(Message);
failedIds.Add(Id);
}
}
}
catch (Exception ex)
{
lock (sb)
{
sb.AppendFormat("System Error Id {0} : {1}", Id, ex.Message);
sb.AppendLine();
}
failedIds.Add(Id);
}
});
return Json(
new
{
IsError = sb.Length != 0,
Message = sb.ToString(),
FailedIds = failedIds
},
JsonRequestBehavior.AllowGet
);
}