Improving the performance of multiple Inserts, Updates, and Deletes via the CRM 2011 Organization Service

UPDATE: Now that Polaris/UR12 are out, the new bulk API is available.  Check out Sonoma Partners blog post on a simple benchmark of the improvements.  Now you can Combine the ne bulk API with client side parallelism to achieve even better performance.  I’ll put that on my ever growing “to blog” list.  However, if you followed this post, then you should be able to figure it out yourself. 

UPDATE: Removed explicitly creating a ConnectionStringSettings object by calling CrmConnection.Parse().

If you are writing any .NET code that interacts with the Organization Service, any insert/update/delete performed happens one at a time, even if you call OrganizationServiceContext.SaveChanges().  This is a perfect candidate to improve performance using the Task Parallel Library.  Here’s a little code snippet to get you started:

var conn = CrmConnection.Parse("Url=;Username=YOURUSERNAME;Password=YOURPASSWORD");
var ctx = new MyDataContext(new OrganizationService(conn));
var query = from a in ctx.AccountSet
            select new Account
                Id = a.Id,
                Name = a.Name,
                Address1_City = a.Address1_City
var tasks = new List<System.Threading.Tasks.Task>();
var accounts = query.ToList();
foreach (var account in accounts)
    // Parallelize each update until BulkAPI is released in UR12
    var task = System.Threading.Tasks.Task.Factory.StartNew(()=>{        
        account.Name += " - UPDATED";                
        account.Address1_City += " - UPDATED";    
        var newctx = new MyDataContext(new OrganizationService(conn));        
//Wait for all the updates executing in parallel to complete.

On my quad core laptop.  The serial version of this code takes a little over 5 seconds.   In comparison, the code above executes in less than a second.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s