0

I am using parallel.foreach in my code to submit multiple url for my application. Initially it work fine but after few day I noticed this exception occurs often. I googled it for many hours but no luck for me.

Explaination: We have Api SMS system from where client submit sms to us and we submit to operators for bulksms. I have 10 URL to submit to specific operator File stop after few seconds with this error. Exception message: One or more errors occurred.

Below is my piece of code.

 Parallel.ForEach(urlList,
    Sub(state, line, index)

      If urlList(index).Sender.ToString = "" Then
          urlList(index).response = "ignore"
      Else
          urlList(index).response = SendHttpRequest(state.url.ToString)
      End If

      urlList(index).url = state.url
    End Sub)

and below is other function which submit HTTP Request.

Public Function SendHttpRequest(ByVal url As String) As String
    Dim responsetext As String = ""
    Try
        Dim webR As WebRequest = HttpWebRequest.Create(url)
        webR.Timeout = 40000
        Dim WebResponse As HttpWebResponse = TryCast(webR.GetResponse(), HttpWebResponse)
        Dim stream As Stream = WebResponse.GetResponseStream()
        Dim reader As New StreamReader(stream)
        responsetext = reader.ReadToEnd()
    Catch ex As Exception
        responsetext = ex.ToString() & vbCrLf
    End Try
    Return responsetext
End Function
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Khurram Shaikh
  • 300
  • 2
  • 14
  • 1
    It's a bit of a concern that you have spent several days on this and seem not to have worked out that an `AggregateException` has an `InnerExceptions` property that is a collection of all the exceptions it is aggregating. You're supposed to examine each exception in that collection to find out what actually happened. – jmcilhinney Jan 29 '19 at 09:53
  • Thank you for response. you mean I should apply try catch on parallel.foreach (first code) and handle inner exceptions. – Khurram Shaikh Jan 29 '19 at 11:57
  • 2
    Where you put an exception handler depends on where you want to handle the exception but I would suggest that it is wrong to return an exception message from a function that is supposed to return text received from a web request. That suggests that, as you said, you should put the `Parallel.ForEach` in a `Try` block, catch the `AggregateException` and then examine each item in its `InnerExceptions` collection. You can then retry just the ones that failed if appropriate or whatever else you like. – jmcilhinney Jan 30 '19 at 03:24
  • @jmcilhinneyThank for the suggestion. I did the same as you said and caught the innerexceptions. Now I can handle exceptions as I required. Thanks again. – Khurram Shaikh Jan 30 '19 at 08:10

0 Answers0