Skip to content

Instantly share code, notes, and snippets.

@ThatRendle
Created February 5, 2013 16:56
Show Gist options
  • Save ThatRendle/4715798 to your computer and use it in GitHub Desktop.
Save ThatRendle/4715798 to your computer and use it in GitHub Desktop.
Await All using operator overloads
namespace AwaitChain
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
Run().Wait();
Console.WriteLine("Done");
}
private static async Task Run()
{
await (Await.All & WaitAndWrite(1) & WaitAndWrite(2) & WaitAndWrite(3));
}
private static Task WaitAndWrite(int n)
{
return Task.Factory.StartNew(() =>
{
Thread.Sleep(n * 100);
Console.WriteLine(n);
});
}
}
public class Await
{
public static readonly Await All = new Await();
private readonly IEnumerable<Task> _tasks;
private Await()
{
_tasks = Enumerable.Empty<Task>();
}
private Await(IEnumerable<Task> tasks, Task newTask)
{
_tasks = new List<Task>(tasks) {newTask};
}
public static Await operator & (Await chain, Task task)
{
return new Await(chain._tasks, task);
}
public TaskAwaiter GetAwaiter()
{
return Task.WhenAll(_tasks).GetAwaiter();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment