1

I have the block of code below where I update a list of users in an async foreach block. Then I have to parse that list of users to another service. The problem is even if I set the users value isRegistered to true, when it gets to the _secondService.UpdateUsers function, the value is still false.

The secondService function has to be outside the foreach. I understand it has something to do with the async, but I have also awaited the second service. Is there a workaround for this?

        userList.ForEach(async user =>
        {
            if (user.isRegistered == false)
            {
                if (await _service.RegisterUser(user))
                {
                    user.isRegistered = true;
                }
            }
        });

        await _secondService.UpdateUsers(userList);
Vida
  • 89
  • 1
  • 8
  • 2
    Don't use `List.Foreach`, use `await foreach` instead. On the other hand, if you use EF Core or a similar ORM, inserting users one by one is a smell - a DbContext tracks all changes and persists *all* of them in a batch when `SaveChanges` is called. You could pass `userList` to that service, have it do its job and then proceed. Batch operations are a lot faster than individual ones too. A single INSERT with 100 rows is more than 100 times faster than 100 individual inserts. It's faster than a batch of 100 INSERTs too – Panagiotis Kanavos Oct 26 '22 at 06:57

1 Answers1

0

Yes @panagiotis answer is right. I changed to the below and it worked:

foreach(var user in userList){
 // do stuffs inside
}
Vida
  • 89
  • 1
  • 8