Solved

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

Posted on 2014-11-04
6
585 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Quiz: What Do These Organizations Have In Common?

Hint: Their teams ended up taking quizzes, too.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

717 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