Which is more efficient Parallell.ForEach or Parallel.ForEachAsync in .NET 8.0 preview

796 Views Asked by At
var tasks = new List<Task<TMDbLib.Objects.Movies.Movie>>();

Parallel.ForEach(page, id =>
{
    var movieFromTmdb = _tmdbClient.GetMovieAsync(id);
    tasks.Add(movieFromTmdb);
});

await Task.WhenAll(tasks);

Or

var moviesBag = new ConcurrentBag<TMDbLib.Objects.Movies.Movie>();
await Parallel.ForEachAsync(page,  async (movieId, token) =>
{
    var movieFromTmdb = await _tmdbClient.GetMovieAsync(movieId, token);

    moviesBag.Add(movieFromTmdb);
});

Edit _tmdbClient.GetMovieAsync is a HTTP Rest call, I am doing pages of 200

1

There are 1 best solutions below

0
Theodor Zoulias On BEST ANSWER

The Parallel.ForEachAsync is the correct API to use. It's not a question of efficiency or performance. There is no comparison to do. The Parallel.ForEach is suitable for doing synchronous work only. Your work is asynchronous, so the Parallel.ForEach is unsuitable. For parallelizing asynchronous work, use the Parallel.ForEachAsync.