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