Reputation: 49
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
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