title: using Parallel.ForEach with/or async/await
body: <p>I try to verify my image URLs to see whether or not they are valid.  I have so many of them that it take hours to complete this task.  Therefore, I decided to do it asynchronously. I would like to know if there are any big differences or advantage of doing my code as below.</p>
  
  <p>My main functions are:</p>
  
  <pre><code>Async Function testUrl_async(ByVal myImageurl As String) As Task(Of Boolean)
  
     myHttpResponse = Await myHttpClient.GetAsync(myImageurl)
      If myHttpResponse.IsSuccessStatusCode Then
          mySuccess = True
      Else
          mySuccess = False
      End If
  
      Return mySuccess
  End Function
  
   Function testUrl(ByVal myImageurl As String) As  Boolean
  
     myHttpResponse = myHttpClient.GetAsync(myImageurl)
      If myHttpResponse.IsSuccessStatusCode Then
          mySuccess = True
      Else
          mySuccess = False
      End If
  
      Return mySuccess
  End Function
  </code></pre>
  
  <p>1) using async await. </p>
  
  <pre><code>For Each myImage In myImages
      Dim result=await testUrl_async(myImageUrl).Result 
      'some code                  
  Next
  </code></pre>
  
  <p>2) using parallel foreach</p>
  
  <pre><code>Parallel.ForEach(myImages, 
      Sub(myImage)
          testUrl(pictureComponent.websiteShop.hqpatronen, myImageUrl) 
          'some code
      End Sub)
  </code></pre>
  
  <p>3) using parallel foreach and asnyc/await</p>
  
  <pre><code>Parallel.ForEach(myImages, 
      Sub(myImage)
          await testUrl_async(pictureComponent.websiteShop.hqpatronen, myImageUrl) 
      'some code
      End Sub)
  </code></pre>
  
  <p>The third one could be the best solution, but it will not allow me to call <code>Await</code>/<code>Async</code> within the <code>ForEach</code>. </p>
  
  <p>If I use the second one, the <code>testurl</code> function has the async http call, but not with <code>Await</code>, thereofore it crashes with the exception message:</p>
  
  <blockquote>
    <p>[TaskCanceledException: A task was canceled.]</p>
  </blockquote>
  
  <p>on the line that calls <code>myHttpClient.GetAsync</code>.  I am guessing that it throws this exception because <code>ForEach</code> has ended and cancellation was requested but httpclient didn't finish its job yet. How can i handle this if this could be the best solution?</p>
  
  <p>Alternatively any other solution which makes my job faster.</p>