1

I want to write an asynchronous Controller that is displaying in output an IEnumerable<IEnumerable<Video>>
I don't know I can manage to write correctly my function Task<IEnumerable<IEnumerable<Video>>> GetVideosAsync(xxxxx) especially the Task.ContinueWhenAll function
(in order not to have blocking code ).
Is it better to use a lambda for this piece of code ...?

  • Can someone help me ?

Nb: *I can only use C#4 and 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>
user1159441
  • 123
  • 2
  • 7
  • With VS2010, you'd use `AsyncManager` for this. Some more details: http://stackoverflow.com/a/21981799/1768303 – noseratio Jun 19 '14 at 02:01

0 Answers0