Intermittent exception when using CRM 2011 early bound APIs via a Threading.Task

Unanswered Intermittent exception when using CRM 2011 early bound APIs via a Threading.Task

  • Wednesday, October 05, 2011 8:57 AM
     
     

    I am experiencing intermittent SaveChangesException when creating CRM entities using the early binding APIs (generated context) via a Threading.Task.

    Using the code below I am able to recreate the exception - note that it is intermittent and I can have several runs without experiencing it.

    As you can see there is no shared state in my code, I am creating the CRM Connection, service and context per operation.

    The exception thrown is:

    Microsoft.Xrm.Sdk.SaveChangesException: An error occured while processing this request. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

    Am I missing something here or are the early bound SDK classes unsafe to use in a multi-threaded environment?

    class Program

        {

            static void Main(string[] args)

            {

                foreach (var index in Enumerable.Range(1, 400))

                {

                    var capturedIndex = index;

                    Task.Factory.StartNew(() => CreateContact(capturedIndex));

                }

     

                Console.Read();

            }

     

            private static void CreateContact(int i)

            {

                var contact = new Contact {FirstName = "Test", LastName = string.Concat("Contact_", i)};

                var context = new XrmServiceContext(new OrganizationService(new CrmConnection("Crm")));  // The generated context is taken from the SDK samples

                context.AddObject(contact);

     

                try

                {

                    context.SaveChanges();

                    Console.WriteLine(string.Concat("Contact created - ", i));

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex);            

                }

            }

        }

All Replies

  • Wednesday, May 02, 2012 11:46 PM
     
     

    Any resolution?  I've seen something somewhat similar to this recently - same exception with CRM, but down in System.Web.Util.CalliHelper.EventArgFunctionCaller ...