0

Web Api HttpClient を使用した次の Async Controller について、皆さんからのフィードバックが欲しいだけです。これは非常に乱雑に見えますが、きれいにする方法はありますか? 複数の非同期タスクを連鎖させるための優れたラッパーを持っている人はいますか?

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 に答える