title: Using PLINQ / TPL in a custom workflow activity
body: <p>I have a workflow defined to execute when a field on a custom entity is changed.
  The workflow calls into a custom activity which in turn uses PLINQ to process a bunch of records.
  The code that the custom activty calls into looks like so:</p>
  
  <blockquote>
  <pre><code>protected override void Execute(CodeActivityContext executionContext)
  {
    // Get the context service.
    IWorkflowContext context = executionContext.GetExtension&lt;IWorkflowContext&gt;();
    IOrganizationServiceFactory serviceFactory =     
    executionContext.GetExtension&lt;IOrganizationServiceFactory&gt;();
  </code></pre>
  </blockquote>
  
  <pre><code> // Use the context service to create an instance of IOrganizationService.
   IOrganizationService _orgService = serviceFactory.CreateOrganizationService  
   (context.InitiatingUserId);
       int pagesize = 2000;
       // use FetchXML aggregate functions to get total count of the number of record to process
       // Reference: http://msdn.microsoft.com/en-us/library/gg309565.aspx
       int totalcount = GetTotalCount();
  
     int totalPages = (int)Math.Ceiling((double)totalcount / (double)pagesize);           
      try
       {
           Parallel.For(1, 
                       totalPages + 1, 
                      () =&gt; new MyOrgserviceContext(_orgService), 
              (pageIndex, state, ctx) =&gt;
               {
  
                  var items = ctx.myEntitySet.Skip((pageIndex - 1) * pagesize).Take(pagesize);
                   foreach(var item in items)
                  {
                      //process item as needed 
                     ctx.SaveChanges();
                  }
                   return ctx;
               },
               ctx =&gt; ctx.Dispose()
               );
       }
       catch (AggregateException ex)
       {
          //handle as needed
       }
   }
  </code></pre>
  
  <p>I'm noticing the following error(s) as an aggregate exception (multiple occurences of the same error in the InnerExceptions):</p>
  
  <p><strong>"Encountered disposed CrmDbConnection when it should not be disposed"</strong></p>
  
  <p>From what I've read:
   <a href="https://stackoverflow.com/questions/9265074/crm-2011-workflow-invalid-pointer-error">CRM 2011 Workflow &quot;Invalid Pointer&quot; error</a></p>
  
  <p>this can happen when you have class level variables since the workflow runtime can end up
   sharing the same class instance across multiple workflow invocations. This is clearly not the case here and also I don't have multiple instances of this workflow running on multiple records. There is just one instance  of this workflow running at any point in time.</p>
  
  <p>The code above works fine when extracted and hosted outside the workflow host (CRMAsyncService).</p>
  
  <p>This is using CRM 2011 Rollup 10.</p>
  
  <p>Any insights much appreciated.</p>