Skip to content

Instantly share code, notes, and snippets.

@mswietlicki
Created July 30, 2013 12:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mswietlicki/6112628 to your computer and use it in GitHub Desktop.
Save mswietlicki/6112628 to your computer and use it in GitHub Desktop.
InCompletionOrder allows you to do foreach on collection of Tasks that will process them as fast as they complete.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Asyncfun
{
public static class AsyncExtensions
{
public static IEnumerable<Task<T>> InCompletionOrder<T>(this IEnumerable<Task<T>> tasks)
{
var inputs = tasks.ToList();
var results = inputs.Select(i => new TaskCompletionSource<T>()).ToList();
int index = -1;
foreach (var task in inputs)
{
task.ContinueWith((t, state) =>
{
var nextResult = results[Interlocked.Increment(ref index)];
nextResult.TrySetResult(t.Result);
}, TaskContinuationOptions.ExecuteSynchronously);
}
return results.Select(r => r.Task);
}
}
}
using System;
using System.Linq;
using System.Net;
namespace Asyncfun
{
class Program
{
static void Main(string[] args)
{
PrintSites();
Console.ReadLine();
}
private static async void PrintSites()
{
var sites = new[] { "https://vimeo.com/68390480", "http://www.google.pl", "https://twitter.com/", "http://www.microsoft.com", "http://mateusz.swietlicki.net", "http://www.google.com" };
var tasks = sites.Select(
async site =>
new
{
Url = site,
Source = await new WebClient().DownloadStringTaskAsync(new Uri(site))
}).ToArray();
foreach (var task in tasks.InCompletionOrder())
{
var site = await task;
Console.WriteLine(site.Url);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment