Solved

MVC 5 Parallel Task List Wait Main Thread Till All Complete?

Posted on 2014-11-04
6
482 Views
Last Modified: 2014-12-10
I know about WaitAll and WhenAll, just cannot get the effect I'm looking for.
The code below begins with a Ajax.ActionLink waiting on it's Action to complete to return the result.
The problem is I cannot successfully get the Action to wait till all the Task in the List are really done.
As-is, the Task run and the Content message returns too soon.
I'm using a msdn code snippet to test the Task List.
I'm using signalr to send status messages to the view.
Could be I have too many async/await in the tasks?

The working code examples use a very simple array like so, and the whenAll works great!
Note: It doesn't seem to matter if the Tasks are returning data for not, the whenAll still works.
        public async Task<ActionResult> CreateMultipleTasksAsyncParallel()
        {
            IHubContext signalr = GlobalHost.ConnectionManager.GetHubContext<ExcelHub>()
            HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1000000 };

            //Works!
            var tasks = new[]
            {
                //Works
                //Task.Run<int>( () => ProcessURLAsync("http://msdn.microsoft.com", client)),
                //Task.Run<int>( () => ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client)),
                //Task.Run<int>( () => ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client))

                //Works!
                Task.Run( () => ProcessURLAsync("http://msdn.microsoft.com", client)),
                Task.Run( () => ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client)),
                Task.Run( () => ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client))
            };
            var results = await Task.WhenAll(tasks);

            return Content("Done!");
       }
      
       async Task<int> ProcessURLAsync(string url, HttpClient client)
        {
            var byteArray = await client.GetByteArrayAsync(url);
            DisplayResults(url, byteArray);
            return byteArray.Length;
        }

        private void DisplayResults(string url, byte[] content)
        {             
            var bytes = content.Length;            
            var displayURL = url.Replace("http://", "");
            signalr.Clients.All.statusMessage(displayURL + " - " + bytes.ToString());
        }

Open in new window


You can see I'm trying to replace the simple array[] with a List or Queue, etc...
@Ajax.ActionLink("Run Tasks", "RunTasks", "Message", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "result", LoadingElementId = "loading" })

[Controller]
IHubContext signalr = GlobalHost.ConnectionManager.GetHubContext<ExcelHub>();

 public async Task<ActionResult> RunTasks()
 {
      HttpClient client = new HttpClient() { MaxResponseContentBufferSize = 1000000 };

            List<Task> list = new List<Task>();

            list.Add(new Task(async() => await ProcessURLAsync("http://msdn.microsoft.com", client)));
            list.Add(new Task(async() => await ProcessURLAsync("http://msdn.microsoft.com/en-us/library/hh156528(VS.110).aspx", client)));
            list.Add(new Task(async () => await ProcessURLAsync("http://msdn.microsoft.com/en-us/library/67w7t67f.aspx", client)));

       list.ForEach(a => a.Start());

       await Task.WhenAll(list); // this does not wait

      return Content("All Task Competed!);
 }   

        async Task<int> ProcessURLAsync(string url, HttpClient client)
        {
            var byteArray = await client.GetByteArrayAsync(url);
            DisplayResults(url, byteArray);
            return byteArray.Length;
        }

        private void DisplayResults(string url, byte[] content)
        {             
            var bytes = content.Length;            
            var displayURL = url.Replace("http://", "");
            signalr.Clients.All.statusMessage(displayURL + " - " + bytes.ToString());
        }

Open in new window

0
Comment
Question by:WorknHardr
  • 4
6 Comments
 
LVL 11

Assisted Solution

by:louisfr
louisfr earned 250 total points
Comment Utility
The methods in the Tasks you put in your list return as soon as the 'await' keyword is reached. You didn't have those 'await' in your working sample.
0
 

Author Comment

by:WorknHardr
Comment Utility
I added those because of VS Intellisence. They don't seem to have any affect on the return.
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
Comment Utility
I think you need to remove the await. As louisfr mentioned, when an await is reached, execution returns immediately to the caller. Your action will return before the tasks finish...well, really there's a race condition, but I'm willing to bet that 99.999999% of the time this is what will happen.

Why should it matter as to whether you use a list or an array of Tasks?

Some good videos on the topic:

http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Three-Essential-Tips-For-Async-Introduction
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:WorknHardr
Comment Utility
Now using Parallel Task Library. Final code snippet coming...
0
 

Accepted Solution

by:
WorknHardr earned 0 total points
Comment Utility
tada...

This example uses SignalR (which I didn't post all the code), but the most important code is here: "Parallel.Invoke"
This example will display two lists (side-by-side) loading independently, with the right-hand list purposefully longer to prove it.
[Controller]
 public async Task<ActionResult> CreateMultipleActionParallelInvoke() //WORKS! -> public ActionResult
        {            
            var list = new List<Action>();
            list.Add(new Action(() => { ProcessInt(110); }));
            list.Add(new Action(() => { ProcessAlpha(1012); }));

            Parallel.Invoke(list.ToArray());

            return Content("Web site download complete");
        }

 void ProcessInt(int end)
        {
            for (int i = 100; i < end; i++)
            {
                Thread.Sleep(250);

                signalr.Clients.All.statusMessage(i.ToString());
            };
        }

        //Action Test
        void ProcessAlpha(int end)
        {
            for (int i=1000; i < end; i++)
            {
                Thread.Sleep(250);

                signalr.Clients.All.errorMessage(i.ToString());
            };
        }

[View]
 @Ajax.ActionLink("Start Multiple Actions Parallel INVOKE", "CreateMultipleActionParallelInvoke", "Message", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "result", LoadingElementId = "loading" })

 <div>
        <div id="loading">
            <img src="~/Content/Images/spinner.gif" height="30" />
        </div>
        <div>
            <div style="float: left">
                <ul id="statusMessage"></ul>
            </div>
            <div style="float: left">
                <ul id="errorMessage"></ul>
            </div>
            <div id="result" style="clear:both">
            </div>
        </div>        
    </div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.2.js"></script>
<script src="~/SignalR/Hubs"></script>

<script type="text/javascript">

    $(function () {
        var array1 = [];
        var excelHub = $.connection.excelHub;
        $.connection.hub.logging = true;
        $.connection.hub.start();
        excelHub.client.statusMessage = function (message) {
            if (array1.indexOf(message) == -1)
            {
                $('#statusMessage').append('<li>' + message + '</li>');
            }
        }

        var array2 = [];
        var excelHub = $.connection.excelHub;
        $.connection.hub.logging = true;
        $.connection.hub.start();
        excelHub.client.errorMessage = function (message) {
            if (array2.indexOf(message) == -1) {
                $('#errorMessage').append('<li>' + message + '</li>');
            }
        }
    }());

    </script>

<style>
    #div1 {
        width: 700px;
        height: 550px;
    }

    ul {
        list-style-type: none;
    }

    div#loading {
        display: none;
        border: none;
        margin: auto;
    }

    #statusMessage {
        color: green;
    }

    #errorMessage {
        color: red;
    }
</style>

[SignalR Hub]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

namespace MVC5_Task_Async_Project.SignalR
{
    public class ExcelHub : Hub
    {
        public ExcelHub()
        {
            Clients.All.statusMessage();
            Clients.All.errorMessage();
        }
    }
}

Open in new window

0
 

Author Closing Comment

by:WorknHardr
Comment Utility
Thx
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now