We help IT Professionals succeed at work.

RAM Usage When Retrieving Dynamics CRM Contact Entity Records

I'm trying to retrieve all the contact entity records in a Dynamics CRM 2016 install via a loop.  I've got a page size of 1,000 but for some reason Microsoft.Xrm.Sdk.EntityReference and Xrm.Contact keep growing in reference count and memory usage after each loop iteration (e.g., Xrm.Contact's reference count grows by 1,000).  Shouldn't each object be wiped after the foreach loop is done?  Each iteration of the while loop adds about 14.6 megabytes to memory usage, eventually causing the program to crash (there's about 160,000 records so 160 iterations).  The code:

        private static void GetAllContactRecords()
        {
            var xrmSC = new Xrm.XrmServiceContext("Xrm");
            int pageSize = 1000;
            int pageNumber = 1;

            var queryEntity = new QueryExpression()
            {
                ColumnSet = new ColumnSet(true),
                EntityName = "contact",
                PageInfo = new PagingInfo()
                {
                    PageNumber = pageNumber,
                    Count = pageSize,
                    PagingCookie = null
                }
            };


            while (true)
            {
                EntityCollection results = xrmSC.RetrieveMultiple(queryEntity);

                if (results.Entities != null)
                {

                    foreach (Xrm.Contact contact in results.Entities)
                    {
                        //do something but commented out for now
                    }
                }
               
                if (results.MoreRecords)
                {
                    queryEntity.PageInfo.PageNumber++;
                    queryEntity.PageInfo.PagingCookie = results.PagingCookie;
                }
                else
                {
                    break;
                }
            }
        }
Comment
Watch Question

Serena HsiMarketing Consultant
BRONZE EXPERT

Commented:
Don't most CRMs have the capability of exporting data to other systems as a built-in function? Microsoft has a walk-through of this. If you are getting the "running out of available memory or disk space" error when opening the file. Save the data file. And then open it in Excel.

Also, is this to create a backup of the data or are you (or some other department) going to edit the data for re-import into Dynamics?

Author

Commented:
This needs to be done as an automated task as it's feeding another system.
Commented:
Had to disable caching as detailed here: https://msdn.microsoft.com/en-us/library/gg695805.aspx

Author

Commented:
Was pointed to the solution elsewhere.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.