-3

I have the following code:

contact.AddressList.ForEach(async (address) => { //...... returnValues = await _apiDataService.CallEndPointAPIAsync( Contact, token, "ContactApiEndpoint"); if (returnValues.Response.StatusCode != System.Net.HttpStatusCode.OK) { //jump out of here } }); 

If for any reason the call, doesn't return ok, I want to jump of here, I thought I'd get away with break; but that's not allowed at this point.

6
  • 7
    Convert to it to a regular "for each". By the way the code inside the foreach block is not awaited in the function it is in since contact.AddressList.ForEach is not awaited. (and can not be) Commented Sep 6, 2023 at 11:01
  • 10
    My advice: never use the ForEach extension, it is really pointless. It doesn't make your code more readable, it's slower since it needs to create a lambda, there are side effects such as closures, and arguably goes against Linq principles (i.e. it's not a query, you can mutate the data) Commented Sep 6, 2023 at 11:14
  • 4
    And it doesn't work properly with async code anyway Commented Sep 6, 2023 at 11:20
  • 1
    @DavidG: ForEach isn't a LINQ extension method, it's an own method of List<T>. Still valid comment though, and I agree. Commented Sep 6, 2023 at 11:25
  • 1
    What are you actually trying to do? Execute these requests one after the other and stop when at the first failing? Then use a standard for or foreach loop. Execute them in parallel? Then what happens to the other requests, when one fails? Commented Sep 6, 2023 at 12:07

1 Answer 1

1

You can't.

Just use a normal foreach loop as mentioned in various comments:

foreach (var address in contact.AddressList) { ...... returnValues = await _apiDataService.CallEndPointAPIAsync(Contact, token, "ContactApiEndpoint"); if (returnValues.Response.StatusCode != System.Net.HttpStatusCode.OK) { break; } } 
Sign up to request clarification or add additional context in comments.

9 Comments

however that will effectivly run all the tasks synchronously one after the other. We don't know if that is a problem, though.
@MakePeaceGreatAgain So does for ForEach - It's not Parallel.ForEach
@YungDeiza but not if the Action passed into ForEach is async. In that case, it will just start each of the actions but don't await them ...
​​@MakePeaceGreatAgain it's sequentially, not synchronously. The tasks run sequentially one after the other.
This one does it...I dont need to do it parallel as there will only be max 5 awaits and the idea is that I want to stop if any fail.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.