英文:
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<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
得分: 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论