title: Running async function in parallel using LINQ's AsParallel()
body: <p>I have a Document DB repository class that has one get method like below:</p>
  
  <pre><code>private static DocumentClient client;
  public async Task&lt;TEntity&gt; Get(string id, string partitionKey = null)
  {
      try
      {
          RequestOptions requestOptions = null;
          if (partitionKey != null)
          {
              requestOptions = new RequestOptions { PartitionKey = new PartitionKey(partitionKey) };
          }
  
          var result = await client.ReadDocumentAsync(
              UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id),
              requestOptions);
          return (TEntity)(dynamic)result.Resource;
      }
      catch (DocumentClientException e)
      {
          // Have logic for different exceptions actually
          throw;
      }
  }
  </code></pre>
  
  <p>I have two collections - Collection1 and Collection2. Collection1 is non-partitioned whereas Collection2 is partitioned.</p>
  
  <p>On the client side, I create two repository objects, one for each collection.</p>
  
  <pre><code>private static DocumentDBRepository&lt;Collection1Item&gt; collection1Repository = new DocumentDBRepository&lt;Collection1Item&gt;("Collection1");
  private static DocumentDBRepository&lt;Collection2Item&gt; collection2Repository = new DocumentDBRepository&lt;Collection2Item&gt;("Collection2");
  
  List&lt;Collection1Item&gt; collection1Items = await collection1Repository.GetItemsFromCollection1(); // Selects first forty documents based on time
  
  List&lt;UIItem&gt; uiItems = new List&lt;UIItem&gt;();
  foreach (var item in collection1Items)
  {
      var collection2Item = await storageRepository.Get(item.Collection2Reference, item.TargetId);    // TargetId is my partition key for Collection2
      uiItems.Add(new UIItem
      {
          ItemId = item.ItemId,
          Collection1Reference = item.Id,
          TargetId = item.TargetId,        
          Collection2Reference = item.Collection2Reference,
          Value = collection2Item.Value
      });
  }
  </code></pre>
  
  <p>This works fine. But since it is happening sequentially with foreach, I wanted to do those Get calls in parallel. When I do it in parallel as below:</p>
  
  <pre><code>ConcurrentBag&lt;UIItem&gt; uiItems = new ConcurrentBag&lt;UIItem&gt;();
  collection1Items.AsParallel().ForAll(async item =&gt; {
      var collection2Item = await storageRepository.Get(item.Collection2Reference, item.TargetId);    // TargetId is my partition key for Collection2
      uiItems.Add(new UIItem
      {
          ItemId = item.ItemId,
          Collection1Reference = item.Id,
          TargetId = item.TargetId,        
          Collection2Reference = item.Collection2Reference,
          Value = collection2Item.Value
      });
    }
  );
  </code></pre>
  
  <p>It doesn't work and <strong><em>uiItems</em></strong> is always empty.</p>