Skip to content

Instantly share code, notes, and snippets.

@retran
Created June 7, 2018 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retran/10b3e6df4c755416732b21206d931d25 to your computer and use it in GitHub Desktop.
Save retran/10b3e6df4c755416732b21206d931d25 to your computer and use it in GitHub Desktop.
C# cooperative multitasking
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<bool> Coroutine1()
{
int i = 0;
while (i < 100)
{
i += 2;
Console.WriteLine("Coroutine1: {0}", i);
yield return true;
}
Console.WriteLine("Coroutine1 finished");
}
public static IEnumerable<bool> Coroutine2()
{
int i = 0;
while (i < 100)
{
i++;
Console.WriteLine("Coroutine2: {0}", i);
yield return true;
}
Console.WriteLine("Coroutine2 finished");
}
public static void Schedule(List<IEnumerator<bool>> coroutines)
{
bool finished = false;
while (!finished)
{
finished = true;
foreach (var coroutine in coroutines)
{
if (coroutine.MoveNext())
{
finished = false;
}
}
}
}
public static void Main()
{
List<IEnumerator<bool>> coroutines = new List<IEnumerator<bool>>()
{
Coroutine1().GetEnumerator(),
Coroutine2().GetEnumerator()
};
Schedule(coroutines);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment