Skip to content

Instantly share code, notes, and snippets.

public class Coordinator<T> {
private readonly Queue<IEnumerator> _coroutines = new Queue<IEnumerator>();
public Coordinator(IEnumerable<Func<Coordinator<T>, IEnumerator>> coroutines) {
// add all coroutines to our queue of coroutines to execute
foreach(var coroutine in coroutines) {
_coroutines.Enqueue(coroutine(this));
}
class Exponentiator {
public static IEnumerator Coroutine(Coordinator<int[]> coordinator) {
while(true) {
if(coordinator.State == null) {
continue;
}
if(coordinator.State.Length == 0) {
Console.WriteLine("consumer finished, end of input");
yield break;
}
class Consumer {
public static IEnumerator Coroutine(int[,] destination, Coordinator<int[]> coordinator) {
Console.WriteLine("consumer started");
int i = 0, j = 0;
while(true) {
Console.WriteLine("yielding to producer");
yield return null;
if(coordinator.State == null) {
continue;
}
class Producer {
public static IEnumerator Coroutine(int[,] source, Coordinator<int[]> coordinator) {
Console.WriteLine("producer started");
for(var i = 0; i < source.GetLength(0); i++) {
coordinator.State = new int[source.GetLength(1)];
for(var j = 0; j < source.GetLength(1); j++) {
coordinator.State[j] = source[i, j];
Console.WriteLine("read {0} from [{1},{2}]", source[i, j], i, j);
}
Console.WriteLine("yielding to consumer");
public IEnumerator SampleCoroutine(Coordinator<T> coordinator) {
while(someCondition) {
// do some work
// yield execution to coordinator
yield return null;
}
}
var source = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
var destination = new int[6, 2];
var coordinator = new Coordinator<int[]>(
new Func<Coordinator<int[]>, IEnumerator>[] {
// Curry coroutine into common "shape"
c => Producer.Coroutine(source, c),
Exponentiator.Coroutine,
c => Consumer.Coroutine(destination, c)
}
@sdether
sdether / gist:1052544
Created June 28, 2011 23:59
Better not rely on this behavior...
[Test]
public void Building_dictionary_from_ordered_list_preserves_key_order() {
var d = new Dictionary<string, string>() {
{"x", "x"},
{"a","a"},
{"g","g"},
{"b","b"}
};
Console.WriteLine("original order: " + string.Join("&", d.Select(x => x.Key + "=" + x.Value).ToArray()));
d = d.OrderBy(x => x.Key, StringComparer.Ordinal).ToDictionary(k => k.Key, v => v.Value);