Last active
September 5, 2015 20:51
-
-
Save tarasn/316ee41f398d43be71d7 to your computer and use it in GitHub Desktop.
[TPL] Wait for all tasks to finish ,but process result as each one completes ("WaitAllOneByOne" pattern ) .Use when some may fail and need to discard or retry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Threading.Tasks; | |
| namespace ConsoleApplication1 | |
| { | |
| internal class Program | |
| { | |
| private static void Main(string[] args) | |
| { | |
| var tasks = new List<Task<int>>(); | |
| for (var i = 0; i < 10; i++) | |
| { | |
| //start 10 tasks | |
| tasks.Add(Task.Factory.StartNew(() => { return DoSomeLongCalculation(); })); | |
| } | |
| while (tasks.Count > 0) //wait for all , one by one | |
| { | |
| var index = Task.WaitAny(tasks.ToArray()); | |
| //do something with the result | |
| var result = tasks[index].Result; | |
| tasks.RemoveAt(index); | |
| } | |
| Console.ReadLine(); | |
| } | |
| private static int DoSomeLongCalculation() | |
| { | |
| throw new NotImplementedException(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment