我想编写一个在输出中显示IEnumerable<IEnumerable<Video>>
的异步控制器
我不知道我可以设法正确编写我的功能 Task<IEnumerable<IEnumerable<Video>>> GetVideosAsync(xxxxx)
,尤其是Task.ContinueWhenAll函数
(为了不使用阻止代码)。
为这段代码使用lambda更好吗?
Nb:*我只能使用C#4和Visual Studio 2010
public class HomeController : AsyncController
{
string[] sources = {
"http://xxxx/membervideos/1",
"http://xxxx/membervideos/2"
};
public Task<ActionResult> Async()
{
var sw = Stopwatch.StartNew();
var data = GetVideosAsync();
sw.Stop();
ViewBag.Elapsed = sw.ElapsedMilliseconds;
return View("~/views/home/index.cshtml", data);
}
Task<IEnumerable<IEnumerable<Video>>> GetVideosAsync()
{
var allVideosTasks = new List<Task<IEnumerable<Video>>>();
foreach (var url in sources)
{
allVideosTasks.Add(DownloadDataAsync(url));
}
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.ContinueWhenAll<IEnumerable<Video>,IEnumerable<IEnumerable<Video>>(
/// CODE TO ComplETE HERE
);
Task<IEnumerable<Video>> DownloadDataAsync(string url)
{
var httpClient = new HttpClient();
var httpResponseMessage = httpClient.GetAsync(url);
var result = httpResponseMessage.ContinueWith
(t =>
{
t.Result.EnsureSuccessStatusCode();
return t.Result.Content.ReadAsAsync<IEnumerable<Video>>();
}
).Unwrap();
return result;
}
/**** VIEW ******/
@{
ViewBag.Title = "Home Page";
}
@model IEnumerable<IEnumerable<MvcApplication1.Models.Video>>
<table>
@foreach (var memberVideos in Model)
{
<tr>
@foreach(var video in memberVideos){
<td>
<div>@video.Title</div>
<div><img src="http://xxxxxx/membervideos/@video.ImageUrl" style="width: 185px;"/> </div>
</td>
}
</tr>
}
</table>
<h1>@ViewBag.Elapsed</h1>