Created
July 30, 2013 12:52
-
-
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.
This file contains 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.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); | |
} | |
} | |
} |
This file contains 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.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