Created
June 7, 2018 14:18
-
-
Save retran/10b3e6df4c755416732b21206d931d25 to your computer and use it in GitHub Desktop.
C# cooperative multitasking
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; | |
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