How to get List<obj> from async Task<List<obj>>

I have this code to fetch an RSS feed async via HttpClient. How do I call this from an MVC controller and pass the data back to the view as a List<RssFeedItem>?

public class RssManager
{
    public async Task<List<RssFeedItem>> GetFeedItems(string url)
    {
        List<RssFeedItem> result = await ReadFeed(url);
        return result;
    }

    public async Task<List<RssFeedItem>> ReadFeed(string url)
    {
        List<RssFeedItem> rssFeedItems = new List<RssFeedItem>();
        string result;

        using (var httpClient = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var response = await httpClient.SendAsync(request);
            result = response.Content.ReadAsStringAsync().Result;
        }

        XmlTextReader rssFeed = new XmlTextReader(result.ToString());
        XmlSerializer deserializer = new XmlSerializer(typeof(List<RssFeedItem>));
        rssFeedItems = (List<RssFeedItem>)deserializer.Deserialize(rssFeed);
        rssFeed.Close();
        rssFeed.Dispose();

        return rssFeedItems;
    }
}
Jon Skeet
people
quotationmark

How do I call this from an MVC controller and pass the data back to the view as a List<RssFeedItem>?

Usually, you'd do this in another async method, and await the result. For example:

public async Task<ActionResult> Foo(...)
{
    // ...
    var list = await manager.ReadFeed(url);
    // ... maybe do something with the list
    return View(list);
}

In general, asynchrony is easier to handle if you don't need to switch between synchronous and asynchronous code. Here, the compiler will register the appropriate callback for the rest of your method to execute when the task returned by ReadFeed has completed, and it will create a Task<ActionResult> that will itself complete when you've provided the view. The ASP.NET infrastructre wlil handle the rest.

people

See more on this question at Stackoverflow