title: How to use await in a parallel foreach?
body: <p>So I spent the better part of the night trying to figure this out.</p>
  <p>I was fortunate to get introduced to  <code>Parallel.ForEach</code> yesterday and it works like I want it to do except from one detail.</p>
  <p>I have the following:</p>
  <pre class="lang-csharp prettyprint-override"><code>Parallel.ForEach(data, (d) =&gt;
  {
      try
      {
          MyMethod(d, measurements);
      }
      catch (Exception e)
      {
          // log
      }
  });
  </code></pre>
  <p>Within the method &quot;MyMethod&quot; I have a lot of logic that gets done and most of it is fine but I make API calls where I fetch data and I use an <code>async</code> task for this to be able to use <code>await</code> in order for the code to wait until that specific part gets executed and then move on:</p>
  <pre class="lang-csharp prettyprint-override"><code>private async void MyMethod(PimData pimData, IEnumerable&lt;ProductMeasurements&gt; measurements)
  {
      try
      {
          // a lot of logic but most relevant part 
  
          await Task.WhenAll(ExecuteMeasurmentAndChartLogic(pimData.ProductNumber, entity));
  
          await Task.WhenAll(resourceImportManager.HandleEntityImageFiles(pimData.ProductType + pimData.ProductSize,SwepImageType.Png, ResourceFileTypes.ThreeD, entity, LinkTypeId.ProductResource));
  
          await Task.WhenAll(resourceImportManager.HandleEntityImageFiles(pimData.ProductSketch, SwepImageType.Png, ResourceFileTypes.Sketch, entity, LinkTypeId.ProductResource));
  
      }
      catch (Exception e)
      {
          // log
      }
  }
  </code></pre>
  <blockquote>
  <p><strong>Problems</strong>:</p>
  <p>1 For starters the loop finishes before all code is finished</p>
  <p>2 Second problem is that I get &quot;Task was cancelled&quot; in a lot of API calls</p>
  <p>3 And third as mentioned above, the code does not wait for each method to fully execute.</p>
  </blockquote>
  <p>I cant get it to execute everything in <code>ExecuteMeasurmentAndChartLogic()</code> method
  before moving forward to the next step.</p>
  <p>This gives me the following issues (more issues):</p>
  <p>In this method I create an item and add it to the db, and this item needs more info that I get from an API call that is done inside of <code>ExecuteMeasurmentAndChartLogic()</code> but the problem is that several items get created and have to wait for the rest of the data which is not what I desire.</p>
  <p><em>SIDE-NOTE: I am aware that creating an item and adding to the db before all data is there is not best practice but I am integrating toward PIM and the process for that is delicate</em></p>
  <p>I want several threads running but at the same time I want the full logic to execute for each item before moving on to the next method.</p>
  <p>Clarification:</p>
  <p>Several items running</p>
  <p>Each item handles <strong>ALL</strong> the logic it needs to handle before moving on to the next part of the code. Normally do this with <code>await</code>.</p>
  <p>In the code above <code>resourceImportManager()</code> method gets executed before <code>ExecuteMeasurmentAndChartLogic()</code> is finished, which is what I don't want.</p>
  <p>Instead of a <code>Parallel.ForEach</code> I used :</p>
  <pre class="lang-csharp prettyprint-override"><code>Task task1 = Task.Factory.StartNew(() =&gt; MyMethod(data, measurements));
  Task.WaitAll(task1);
  </code></pre>
  <p>But that wasn't much of a help.</p>
  <p>Fairly new to this and haven't been able to understand where I am doing it wrong.</p>
  <p>EDIT:
  Updated the problems with this</p>
  <p>EDIT: this is how <code>ExecuteMeasurmentAndChartLogic()</code> looks:</p>
  <pre class="lang-csharp prettyprint-override"><code>public async Task ExecuteMeasurmentAndChartLogic(string productNumber, Entity entity)
  {
      try
      {
          GrafGeneratorManager grafManager = new GrafGeneratorManager();
          var graphMeasurmentList = await MeasurmentHandler.GetMeasurments(productNumber);
  
          if (graphMeasurmentList.Count == 0) return;
  
          var chart = await grafManager.GenerateChart(500, 950, SystemColors.Window, ChartColorPalette.EarthTones,
                      &quot;legend&quot;, graphMeasurmentList);
  
          await AddChartsAndAddToXpc(chart, entity, productNumber);
      }
      catch (Exception e)
      {
          Console.WriteLine(e);
      }
  }
  </code></pre>
  <p>EDIT:
  Background to this:
  I make a call to an API to get a lot of data. For each item in this data I need to make an API call and get data that I apply to the item.</p>
  <p>After reading comments which also got me thinking in a different way. I can perhaps loop through all my items and do minor logic for them and add a URL in a task list and make a separate task that executes this one by one.</p>
  <p>Will keep this updated</p>