C#Web Api GetAsync + MVC 3.0异步控制器

时间:2011-07-12 15:26:08

标签: c# asynchronous wcf-web-api

我只想让每个人使用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);
    }
}

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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)的示例,用于链接异步操作。