1

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
    );
}
Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
praveen
  • 55
  • 11
  • 1
    Which line is throwing the NRE? As you're locking on all other parts of the code, I'd say it must likely due to your database not being able to handle parallelism, meaning it isn't thread safe. – Yuval Itzchakov Oct 27 '15 at 07:48
  • 1
    If your intent with this code is to speed things up you're doing the opposite. Locking on every iteration of the loop will make it slower than just doing a plain `foreach`. – Enigmativity Oct 27 '15 at 07:52
  • Two Issues: - You have shared Data structure, which gets nullified by one thread and others throw the Null reference or similar exception - Use Lock in parallel call is absolutely necessary, else it will make all threads go in serial mode, even when logging the errors – Mrinal Kamboj Oct 27 '15 at 07:53

0 Answers0