Parallel.ForEach不循环

时间:2015-10-27 07:46:27

标签: c# multithreading parallel.foreach

我有一个方法可以将id列表插入数据库。我已经使用Parallel.ForEach来加速进程,但是它将一条记录插入Databse并生成对象引用,而不是设置为其余记录的对象实例,但是同样适用于foreach循环。

这是我的方法。

[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
    );
}

0 个答案:

没有答案
相关问题