Stop Using .ForEach with await! Here’s the Right Way in C# 💻

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

i encountered this problem exactly when you posted this video, thanks very much !!!

veniaminbalan
Автор

I can count on one hand the times I have used List.ForEach in C# and I've used it for more than 10 years.

Your example "fetchFromDatabase" would in practice be written by passing the list of ids in and batch requesting .where(contains) (or whatever db fetch strategy is optimal), which gives you the option of using IAsyncEnumerable, the way it's written you're making N calls to the database

orterves
Автор

There’s no need to use Parallel class for asynchronous calls. Instead don’t await on individual tasks, rather do a WhenAll or WhenAny as others have pointed it out. Or with net 9 there is a WhenEach variant allowing asynchronous await on all the tasks in any order they complete. The reason for not using Parallel class is due to the implementation difference between
I/O bound and CPU bound threads. Asynchronous operations are implemented via a thread pool taking into account the fact the COU is mostly unused for the duration of the call. CPU bound work is done on parallel threads mapped directly to the logical CPU cores.

eugenpaval
Автор

You should be able to do a WhenAll and Select, then an OrderBy on the whole thing. Something like this:

var numbers = new List<int> { 1, 2, 3, 4 };

(await (n, index) =>
{
await Task.Delay(250);
return new { Index = index, Value = n };
})))
.OrderBy(result => result.Index)
.ToList()
.ForEach(result =>

dasfahrer
Автор

You should probably be using ConcurrentBag for your last example. I know it's a bit out of scope but just be correct. Other than that, great video!

zagoskintoto
Автор

Sorry, but I do not think you are comparing the same thing. The reason the list.foreach(async...) code did not return anything is because the program terminated right away. If you add a console.ReadLine() at the end, this will allow the tasks created in the loop to do their thing and should display the results.

knightmarerip
Автор

Could you create a video about using Radzen within MAUI Blazor?

kevman
Автор

Thx a lot for your video,
Can you use parallel if you call a repository with a dbcontext ?

padnom
Автор

what if we want to send multiple HttpClient requests

WeirdoPlays