Читать книгу Dojos für Entwickler 2 - Stefan Lieser - Страница 65
Listing 13 Der Gather-Baustein.
Оглавлениеpublic class Gather<T> { private bool resultWasRaised; private readonly BlockingCollection<T> queue = new BlockingCollection<T>(); private bool intpu1IsEmpty; private bool intpu2IsEmpty; public void Input1(IEnumerable<T> input) { RaiseResultEvent(); Iterate(input); intpu1IsEmpty = true; if(intpu1IsEmpty && intpu2IsEmpty) { queue.CompleteAdding(); } } } public void Input2(IEnumerable<T> input) { RaiseResultEvent(); Iterate(input); intpu2IsEmpty = true; if (intpu1IsEmpty && intpu2IsEmpty) { queue.CompleteAdding(); } } private void Iterate(IEnumerable<T> input) { foreach (var t in input) { queue.Add(t); } } private void RaiseResultEvent() { if (resultWasRaised) { return; } resultWasRaised = true; var thread = new Thread(x => Result(EnumerateTheQueue())); thread.Start(); } private IEnumerable<T> EnumerateTheQueue() { foreach (var item in queue.GetConsumingEnumerable()) { yield return item; } } public event Action<IEnumerable<T>> Result; }