Skip to content

Instantly share code, notes, and snippets.

@tarasn
Last active September 5, 2015 20:51
Show Gist options
  • Save tarasn/316ee41f398d43be71d7 to your computer and use it in GitHub Desktop.
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
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