Created
February 5, 2013 16:56
-
-
Save ThatRendle/4715798 to your computer and use it in GitHub Desktop.
Await All using operator overloads
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
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