3 // Copyright (c) 2011 Jérémie "garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 using System.Threading.Tasks;
28 using System.Collections.Generic;
29 using System.Collections.Concurrent;
31 namespace System.Threading.Tasks.Dataflow
33 internal class ChooserBlock<T1, T2, T3>
35 class ChooseTarget<TMessage> : ITargetBlock<TMessage>
37 Action<TMessage> messageArrived;
39 public ChooseTarget (Action<TMessage> messageArrived)
41 this.messageArrived = messageArrived;
44 public DataflowMessageStatus OfferMessage (DataflowMessageHeader messageHeader,
45 TMessage messageValue,
46 ISourceBlock<TMessage> source,
49 messageArrived (messageValue);
50 return DataflowMessageStatus.Accepted;
53 public Task Completion {
59 public void Complete ()
64 public void Fault (Exception ex)
70 TaskCompletionSource<int> completion = new TaskCompletionSource<int> ();
72 public ChooserBlock (Action<T1> action1, Action<T2> action2, Action<T3> action3, DataflowBlockOptions dataflowBlockOptions)
74 // TODO: take care of options and its cancellation token
76 Target1 = new ChooseTarget<T1> (message => MessageArrived (0, action1, message));
77 Target2 = new ChooseTarget<T2> (message => MessageArrived (1, action2, message));
78 Target3 = new ChooseTarget<T3> (message => MessageArrived (2, action3, message));
81 void MessageArrived<TMessage> (int index, Action<TMessage> action, TMessage value)
85 completion.SetResult (index);
86 } catch (Exception e) {
87 completion.SetException (e);
91 public ITargetBlock<T1> Target1 {
96 public ITargetBlock<T2> Target2 {
101 public ITargetBlock<T3> Target3 {
106 public Task<int> Completion {
108 return completion.Task;