C# 4.0 C#4中的异步任务控制器
我想编写一个异步控制器,在输出中显示C# 4.0 C#4中的异步任务控制器,c#-4.0,asynchronous,C# 4.0,Asynchronous,我想编写一个异步控制器,在输出中显示IEnumerable 我不知道我能否正确编写我的函数任务GetVideosAsync(xxxxx)尤其是任务。继续所有函数(以避免出现阻塞代码)。 对这段代码使用lambda更好吗 有人能帮我吗 Nb:*我只能使用C#4和visual Studio 2010 public class HomeController : AsyncController { string[] sources = {
IEnumerable
我不知道我能否正确编写我的函数
任务GetVideosAsync(xxxxx)
尤其是任务。继续所有函数(以避免出现阻塞代码)。
对这段代码使用lambda更好吗
- 有人能帮我吗
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>
公共类HomeController:AsyncController
{
字符串[]源={
"http://xxxx/membervideos/1",
"http://xxxx/membervideos/2"
};
公共任务异步()
{
var sw=Stopwatch.StartNew();
var data=GetVideosAsync();
sw.Stop();
ViewBag.appead=sw.ElapsedMilliseconds;
返回视图(“~/views/home/index.cshtml”,数据);
}
任务GetVideosAsync()
{
var allVideosTasks=新列表();
foreach(源中的var url)
{
Add(下载数据异步(url));
}
var context=TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.continuewhalll
{
t、 Result.EnsureSuccessStatusCode();
返回t.Result.Content.ReadAsAsync();
}
).Unwrap();
返回结果;
}
/****看法******/
@{
ViewBag.Title=“主页”;
}
@模型IEnumerable
@foreach(模型中的视频)
{
@foreach(会员视频中的var视频){
@视频。标题
}
}
@查看包。已过
对于VS2010,您可以使用AsyncManager
进行此操作。更多详细信息: