6

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?

katit
  • 17,375
  • 35
  • 128
  • 256
  • That should be the other way around. It's `WaitAll` that should be excluded from the silverlight API and WhenAll should be included. Do you have the proper version of .NET installed? – Servy Mar 13 '13 at 03:58
  • FWIW, on my stock SL5 I only see `Task.WaitAll`; there is no `Task.WhenAll` I assume unless I install some 3rd party library. – Peter Tirrell Jun 10 '16 at 15:47

2 Answers2

11

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(...);
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
1

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);
    }
});
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96