1
var moviePromises = this.watchlist.Select(async e => await this.GetMovieFromWatchlistEntry(e));

var movies = await Task.WhenAll(moviePromises);

foreach (var movie in movies)
{
   // dostuff
}

When I am doing the following it seems that all tasks created in (GetMovieFromWatchlistEntry) and are executed at the same time. but I want that at each step of the iteration a single task is created and awaited (lazy evaluation). I guess this is possible with IAsyncEnumerable, but how can I create a IAsyncEnumerable from my existing moviePromises enumerable?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
codymanix
  • 28,510
  • 21
  • 92
  • 151
  • 1
    Check out [this](https://stackoverflow.com/questions/35011656/async-await-in-linq-select "Async await in linq select") question, and specifically [this](https://stackoverflow.com/a/66331594/11178549) answer by nfplee. – Theodor Zoulias Jun 23 '23 at 22:02

2 Answers2

2

I want that at each step of the iteration a single task is created and awaited... I guess this is possible with IAsyncEnumerable

IAsyncEnumerable is for when you need to asynchronously determine the length of the sequence. If each item is asynchronous but the length is well-known, then IEnumerable<T> is fine - just enumerate it with foreach and await what you want to do to each item:

foreach (var watchItem in this.watchList)
{
  var movie = await this.GetMovieFromWatchlistEntry(watchItem);
  // dostuff
}

from my existing moviePromises enumerable?

My code above assumes you can change moviePromises. If that's not the case for some reason, then you can still enumerate and await them one at a time like this answer shows. However, if moviePromises at some point in the future has a ToList() or something like that stuck on the end, then all the tasks are started at that time.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
1

I want that at each step of the iteration a single task is created and awaited

So, something like this?

foreach(var moviePromise in moviePromises)
{
    var result = await moviePromise;
    // do stuff on the result
}
Blindy
  • 65,249
  • 10
  • 91
  • 131