Write FAST C# Code - Task.WhenAll vs Parallel.ForEachAsync in DotNet

preview_player
Показать описание
You've found yourself trying to optimize your algorithm and the only way you can see to squeeze out more performance is to run things in parallel. We can use a parallel foreach or we can look at task when all in C#! So, do you go with Task.WhenAll or do you leverage Parallel.ForEachAsync? Let's use BenchmarkDotNet and have the benchmarks speak for themselves.

For more videos on programming with detailed examples, check this out:

Check out more Dev Leader content (including full in-depth articles with source code examples) here:

Social Media:

#dotnet #csharp #benchmark #benchmarkdotnet
Рекомендации по теме
Комментарии
Автор

Hi, good stuff, but i think i find small opsie here,
in BenchmarkSimulatedCpu class TaskWhenAll method is actually running synchronously, when you calling await Task.WhenAll(tasks) all of them are already completed, to make it async you should do:
var tasks = _dataSet!.Select(_ => Task.Run(() =>
{
for (int i = 0; i < CpuWorkIterations; i++)
{
Random.Shared.Next();
}
})).ToArray();

await Task.WhenAll(tasks);

Jeymikuz
Автор

If you're in a situation where a lot of iterated IO bound code was written in an entirely sync context/scope (not good, I know) what can be done? Will wrapping it in a parallel for help? Should you enqueue tasks in a concurrent queue? What's the best way out of this situation?

UNHAPPYMEXICANS
Автор

If you enjoyed this and want to see other videos related to some of the content I was going through (i.e. what I've been trying to optimize), then these videos might be interesting!


✅Like, ✅share, and ✅subscribe to the channel for more full length content about software engineering topics presented by a Principal Software Engineering Manager 🤓

DevLeader