C# Web Api GetAsync + MVC 3.0 Async Controller
本文关键字:Async Controller MVC Web Api GetAsync | 更新日期: 2023-09-27 18:02:31
我只是想让大家反馈关于以下异步控制器使用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);
}
}
您似乎使用了许多异步调用和asyncmanager . outstandingoperations . decincrement()。下面的代码足以使用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);
}
}
您可以查看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)链接异步操作的示例。