Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Created February 14, 2012 14:34
Show Gist options
  • Save StephenCleary/1827115 to your computer and use it in GitHub Desktop.
Save StephenCleary/1827115 to your computer and use it in GitHub Desktop.
Coroutines in VS11
using System;
using System.Linq;
using System.Threading.Tasks;
// Target: .NET 4.5 Client (or Full)
// Add a reference to System.Threading.Tasks.Dataflow
class Program
{
static void Main(string[] args)
{
Coroutines.Run(FirstCoroutine, SecondCoroutine, ThirdCoroutine).Wait();
Console.ReadKey();
}
private static class Coroutines
{
public static async Task Run(params Func<Task>[] coroutines)
{
var factory = new TaskFactory(new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler);
var coroutineStartTasks = coroutines.Select(factory.StartNew);
var coroutineCompleteTasks = await Task.WhenAll(coroutineStartTasks);
await Task.WhenAll(coroutineCompleteTasks);
}
}
private static async Task FirstCoroutine()
{
Console.WriteLine("Starting FirstCoroutine");
Console.WriteLine("Yielding from FirstCoroutine...");
await Task.Yield();
Console.WriteLine("Returned to FirstCoroutine");
Console.WriteLine("Yielding from FirstCoroutine again...");
await Task.Yield();
Console.WriteLine("Returned to FirstCoroutine again");
Console.WriteLine("Finished FirstCoroutine");
}
private static async Task SecondCoroutine()
{
Console.WriteLine(" Starting SecondCoroutine");
Console.WriteLine(" Yielding from SecondCoroutine...");
await Task.Yield();
Console.WriteLine(" Returned to SecondCoroutine");
Console.WriteLine(" Yielding from SecondCoroutine again...");
await Task.Yield();
Console.WriteLine(" Returned to SecondCoroutine again");
Console.WriteLine(" Finished SecondCoroutine");
}
private static async Task ThirdCoroutine()
{
Console.WriteLine(" Starting ThirdCoroutine");
Console.WriteLine(" Yielding from ThirdCoroutine...");
await Task.Yield();
Console.WriteLine(" Returned to ThirdCoroutine");
Console.WriteLine(" Finished ThirdCoroutine");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment