Solved

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

Posted on 2014-11-04
6
543 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
6 Comments
 
LVL 11

Assisted Solution

by:louisfr
louisfr earned 250 total points
ID: 40423386
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
ID: 40423498
I added those because of VS Intellisence. They don't seem to have any affect on the return.
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 40423815
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
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 

Author Comment

by:WorknHardr
ID: 40430788
Now using Parallel Task Library. Final code snippet coming...
0
 

Accepted Solution

by:
WorknHardr earned 0 total points
ID: 40451442
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
ID: 40490920
Thx
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

726 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