Expotr
Expotr

Reputation: 49

How to run a method with Task.WhenAll for every item in list and store the results?

I'm working on an application that retrieves RSS feeds every few minutes and downloads the items on the feeds matching a set of criterias. However, I'm struggling to debug the code below. When I set up breakpoints in my code, it doesn't go past the first line in GoThroughFeeds(). I suspect that there is something wrong with the way I create and handle tasks. Initially, I created the tasks using Task.Run(), but they would run twice (the second batch after the await). What am I doing wrong?

private async void RunOnInterval(TimeSpan delay)
{
  do
  {
    await GoThroughFeeds();
    await Task.Delay(delay);

  } while (true);
}

private async Task GoThroughFeeds()
{
  Feed[] updatedFeeds = await Task
    .WhenAll(Repository.Data.Feeds.Select(feed => new Task<Feed>(() => FetchRss(feed))));

  // Do more stuff with the feeds
}

public Feed FetchRss(Feed feed)
{
  feed.Items = Repository.GetItems(feed);
  return feed;
}

Upvotes: 1

Views: 623

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39027

new Task<Feed>(() => FetchRss(feed)) is wrong. You're trying to wait on a task that isn't started. In fact, the constructor of Task should almost never be used.

Task.FromResult isn't good either, as it'll execute your code synchronously, instead of offloading it to a different thread.

In the end, Task.Run does exactly what you need.

Upvotes: 2

Related Questions