[C#] Coroutine Code Sample
== Coroutine.cs
using System.Collections.Generic;
using System.Collections;
namespace CoroutineTest
{
public class Coroutine
{
private IEnumerator theRoutine;
public Coroutine(IEnumerator routine)
{
this.theRoutine = routine;
}
public bool MoveNext()
{
if (theRoutine.Current is IEnumerator)
if (((IEnumerator)theRoutine.Current).MoveNext())
return true;
return theRoutine.MoveNext();
}
}
public class Coroutines
{
List<Coroutine> routines = new List<Coroutine>();
public Coroutines()
{
}
public Coroutine Start(IEnumerator routine)
{
Coroutine coroutine = new Coroutine(routine);
routines.Add(coroutine);
return coroutine;
}
public void Stop(Coroutine routine)
{
routines.Remove(routine);
}
public void StopAll()
{
routines.Clear();
}
public void Update()
{
for (int i = 0; i < routines.Count; i++)
{
if (routines[i].MoveNext())
continue;
else
routines.RemoveAt(i--);
}
}
public int Count
{
get { return routines.Count; }
}
public bool Running
{
get { return routines.Count > 0; }
}
}
}
== Program.cs
using System;
using System.Collections;
using System.Diagnostics;
namespace CoroutineTest
{
class Program
{
//"Death" by John Donne
const string poem = "\"Death\" by John Donne\n\n" +
"Death be not proud, though some have called thee\n" +
"Mighty and dreadfull, for, thou art not so,\n" +
"For, those, whom thou think'st, thou dost overthrow,\n" +
"Die not, poore death, nor yet canst thou kill me.\n" +
"From rest and sleepe, which but thy pictures bee,\n" +
"Much pleasure, then from thee, much more must flow,\n" +
"And soonest our best men with thee doe goe,\n" +
"Rest of their bones, and soules deliverie.\n" +
"Thou art slave to Fate, Chance, kings, and desperate men,\n" +
"And dost with poyson, warre, and sicknesse dwell,\n" +
"And poppie, or charmes can make us sleepe as well,\n" +
"And better then thy stroake; why swell'st thou then;\n" +
"One short sleepe past, wee wake eternally,\n" +
"And death shall be no more; death, thou shalt die.";
static void Main(string[] args)
{
var coroutines = new Coroutines();
coroutines.Start(WritePoem(poem));
while (coroutines.Running)
coroutines.Update();
//Wait for user input to close
Console.WriteLine("\nPress any key to exit");
Console.ReadLine();
}
static IEnumerator WritePoem(string poem)
{
//Write the poem letter by letter
foreach (var letter in poem)
{
Console.Write(letter);
yield return Wait(0.01f);
}
}
static IEnumerator Wait(float time)
{
var watch = Stopwatch.StartNew();
while (watch.Elapsed.TotalSeconds < time)
yield return 0;
}
}
}