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
Solved

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

Posted on 2014-11-04
6
521 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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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…

809 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