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

huangapple go评论59阅读模式
英文:

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

问题

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);

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 是一个HTTP Rest调用,我正在处理每页的200个。

英文:
var tasks = new List&lt;Task&lt;TMDbLib.Objects.Movies.Movie&gt;&gt;();

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

await Task.WhenAll(tasks);

Or

var moviesBag = new ConcurrentBag&lt;TMDbLib.Objects.Movies.Movie&gt;();
await Parallel.ForEachAsync(page,  async (movieId, token) =&gt;
{
    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

得分: 2

Parallel.ForEachAsync 是正确的API。这不是效率或性能的问题。没有比较可做。Parallel.ForEach 仅适用于同步工作。您的工作是异步的,因此 Parallel.ForEach 不合适。要并行化异步工作,请使用 Parallel.ForEachAsync

英文:

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.

huangapple
  • 本文由 发表于 2023年6月6日 10:01:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定