Execute parallel tasks with async/await

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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?

回答1:

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(...); 


回答2:

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);     } }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!