using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;

namespace nft.framework {
    public delegate IEnumerable FiberTask();
    /// <summary>
    /// ノンプリエンプティブマルチタスク
    /// </summary>
    public class FiberManager {
        List<IEnumerator> fibers = new List<IEnumerator>();
        public int ProcessFibers() {
            for (int i = fibers.Count - 1; i >= 0; i--) {
                IEnumerator en = fibers[i];
                if (!en.MoveNext()) {
                    fibers.RemoveAt(i);
                }
            }
            return fibers.Count;
        }

        public void Add(IEnumerable fiberproc) {
            fibers.Add(fiberproc.GetEnumerator());
        }
    }

    class FiberSample {
        public void Test() {
            FiberManager fm = new FiberManager();
            fm.Add(FiberProc1());
            fm.Add(FiberProc2());
            fm.Add(FiberProc3());
            while (fm.ProcessFibers() > 0) ;
        }

        IEnumerable FiberProc3() {
            for (int i = 1; i < 3; i++) {
                Debug.Print("STEP3-" + i);
                yield return null;
            }
            yield break;
        }

        IEnumerable FiberProc2() {
            for (int i = 1; i < 5; i++) {
                Debug.Print("STEP2-"+i);
                yield return null;
            }
            yield break;
        }

        IEnumerable FiberProc1() {
            Debug.Print("STEP1-1");
            yield return null;
            Debug.Print("STEP1-2");
            yield return null;
            Debug.Print("STEP1-3");
            yield break;
        }
    }
}
