0

我只希望大家对使用 Web Api HttpClient 的以下异步控制器提供反馈。这看起来很乱,有没有办法让它更干净?有没有人有一个很好的将多个异步任务链接在一起的包装器?

public class HomeController : AsyncController
{
    public void IndexAsync()
    {
        var uri = "http://localhost:3018/service";
        var httpClient = new HttpClient(uri);

        AsyncManager.OutstandingOperations.Increment(2);
        httpClient.GetAsync(uri).ContinueWith(r =>
        {
            r.Result.Content.ReadAsAsync<List<string>>().ContinueWith(b =>
            {
                AsyncManager.Parameters["items"] = b.Result;
                AsyncManager.OutstandingOperations.Decrement();
            });
            AsyncManager.OutstandingOperations.Decrement();
        });
    }

    public ActionResult IndexCompleted(List<string> items)
    {
        return View(items);
    }
}
4

2 回答 2

0

您可以查看http://pfelix.wordpress.com/2011/08/05/wcf-web-api-handling-requests-asynchronously/

它包含一个基于任务迭代器技术 ( http://blogs.msdn.com/b/pfxteam/archive/2009/06/30/9809774.aspx ) 的示例,用于链接异步操作。

于 2011-08-07T10:07:19.893 回答
0

您似乎使用了很多异步调用和 AsyncManager.OutstandingOperations.Decrement()。以下代码足以使用 YQL 异步加载 Flickr 照片信息。

public class HomeController : AsyncController
{
    public void IndexAsync()
    {
        var uri = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20flickr.photos.recent";
        var httpClient = new HttpClient(uri);

        AsyncManager.OutstandingOperations.Increment();
        httpClient.GetAsync("").ContinueWith(r =>
            {
                var xml = XElement.Load(r.Result.Content.ContentReadStream);

                var owners = from el in xml.Descendants("photo")
                                select (string)el.Attribute("owner");

                AsyncManager.Parameters["owners"] = owners;
                AsyncManager.OutstandingOperations.Decrement();
            });
    }

    public ActionResult IndexCompleted(IEnumerable<string> owners)
    {
        return View(owners);
    }
}
于 2011-07-13T09:05:17.510 回答