Solved

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

Posted on 2014-11-04
6
494 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
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

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 …
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.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

911 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

23 Experts available now in Live!

Get 1:1 Help Now