C# 使用Parallel.ForEach插入和更新CRM数据

C# 使用Parallel.ForEach插入和更新CRM数据,c#,for-loop,parallel-processing,dynamics-crm-2011,dynamics-crm,C#,For Loop,Parallel Processing,Dynamics Crm 2011,Dynamics Crm,我需要从外部表更新CRM数据。一切正常,但速度很慢。这是我的代码: static void Main(string[] args) { var dbClient = new CollectionEntities(); //Get database Entities using(var xrm = new XrmServiceContext("Xrm"); // Get CRM Entities { foreach (var row in dbClient.Client) //Readin

我需要从外部表更新CRM数据。一切正常,但速度很慢。这是我的代码:

static void Main(string[] args)
{
var dbClient = new CollectionEntities(); //Get database Entities
using(var xrm = new XrmServiceContext("Xrm"); // Get CRM Entities
    {
foreach (var row in dbClient.Client) //Reading rows from database
{
var c = (from a in crm.new_clientSet where a.new_Idnumber == row.Client_ID select a).FirstOrDefault(); // IS there clint with id from database
                            if (c == null)// if client not exist i create new if exists I update data
                            {
                                c = new new_client { new_Idnumber = row.Client_ID };
                                crm.AddObject(c);
                            }
                            c.new_name = row.Client_name; //[Client_name]
                            c.new_Idnumber = row.Client_ID;//[Client_ID]
                            c.EmailAddress = row.Email;//[Email]
                xrm.AddObject(c);
                    xrm.SaveChanges();

}
}
}

有了它,我可以在CRM中插入和更新数据,但速度会变慢。有没有办法使用Parallel.ForEach方法或其他方法来加速此过程?谢谢

您正在每个循环中从CRM加载一行。这使得你的应用程序非常“健谈”,而且它在网络开销上花费的时间比加载数据要多。尝试在循环之前使用单个查询将整个CRM数据集加载到内存中。然后,在循环中,从内存中查找记录,而不是查询CRM。如果数据集很大,可能需要使用分页cookies。

请查看Microsoft Premier Field Engineering-Dynamics团队的开源库。它为您处理并行性。示例页面显示了并行更新一组记录是多么容易:

public void ParallelUpdate(List<Entity> targets)
{
    try
    {
        this.Manager.ParallelProxy.Update(targets);
    }
    catch (AggregateException ae)
    {
        // Handle exceptions
    }
}
public更新(列出目标)
{
尝试
{
this.Manager.ParallelProxy.Update(目标);
}
捕获(聚合异常ae)
{
//处理异常
}
}
您还可以使用它来查询大型数据集……它将为您检索所有内容。

在这种情况下肯定是一种方法

不同之处在于,您将发送一个请求,这样您就不会有网络开销,而且,您的所有插入都将由CRM在服务器端处理,速度更快