Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute parallel tasks with async/await

I need to execute multiple async tasks in Silverlight.

Documentation of the 3rd party package states I can use

await Task.WhenAll()

Unfortunately silverlight only have Task.WaitAll() and it is not awaitable. If I try to use it I get deadlock (I assume - because whole thing freezes)

What is the proper pattern to use in async method?

like image 555
katit Avatar asked Mar 13 '13 02:03

katit


2 Answers

For Silverlight I assume you're using the Microsoft.Bcl.Async package.

Since this (add-on) package cannot modify the (built-in) Task type, you'll find some useful methods in the TaskEx type. Including WhenAll:

await TaskEx.WhenAll(...);
like image 66
Stephen Cleary Avatar answered Sep 20 '22 10:09

Stephen Cleary


I think that you could try to use TaskFactory.ContinueWhenAll to have similar behaviour if I understand your question correctly. Example:

var task1 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(1000);
    return "dummy value 1";
});

var task2 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(2000);
    return "dummy value 2";
});

var task3 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(3000);
    return "dummy value 3";
});

Task.Factory.ContinueWhenAll(new[] { task1, task2, task3 }, tasks =>
{
    foreach (Task<string> task in tasks)
    {
        Console.WriteLine(task.Result);
    }
});
like image 28
Petr Abdulin Avatar answered Sep 19 '22 10:09

Petr Abdulin