3 // Copyright (c) 2011 Jérémie "garuma" Laval
4 // Copyright (c) 2012 Petr Onderka
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 using System.Collections.Generic;
25 using System.Collections.Concurrent;
27 namespace System.Threading.Tasks.Dataflow {
28 public sealed class TransformBlock<TInput, TOutput> :
29 IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput> {
30 readonly ExecutionDataflowBlockOptions dataflowBlockOptions;
31 readonly CompletionHelper compHelper;
32 readonly BlockingCollection<TInput> messageQueue = new BlockingCollection<TInput> ();
33 readonly MessageBox<TInput> messageBox;
34 readonly OutgoingQueue<TOutput> outgoing;
35 readonly Func<TInput, TOutput> transform;
36 readonly Func<TInput, Task<TOutput>> asyncTransform;
38 TransformBlock (ExecutionDataflowBlockOptions dataflowBlockOptions)
40 if (dataflowBlockOptions == null)
41 throw new ArgumentNullException ("dataflowBlockOptions");
43 this.dataflowBlockOptions = dataflowBlockOptions;
44 this.compHelper = new CompletionHelper (dataflowBlockOptions);
47 public TransformBlock (Func<TInput, TOutput> transform)
48 : this (transform, ExecutionDataflowBlockOptions.Default)
52 public TransformBlock (Func<TInput, TOutput> transform,
53 ExecutionDataflowBlockOptions dataflowBlockOptions)
54 : this (dataflowBlockOptions)
56 if (transform == null)
57 throw new ArgumentNullException("transform");
59 this.transform = transform;
60 this.messageBox = new ExecutingMessageBox<TInput> (
61 this, messageQueue, compHelper,
62 () => outgoing.IsCompleted, TransformProcess, () => outgoing.Complete (),
63 dataflowBlockOptions);
64 this.outgoing = new OutgoingQueue<TOutput> (this, compHelper,
65 () => messageQueue.IsCompleted, messageBox.DecreaseCount,
66 dataflowBlockOptions);
69 public TransformBlock(Func<TInput, Task<TOutput>> transform)
70 : this(transform, ExecutionDataflowBlockOptions.Default)
74 public TransformBlock (Func<TInput, Task<TOutput>> transform,
75 ExecutionDataflowBlockOptions dataflowBlockOptions)
76 : this (dataflowBlockOptions)
78 if (transform == null)
79 throw new ArgumentNullException("transform");
81 this.asyncTransform = transform;
82 this.messageBox = new AsyncExecutingMessageBox<TInput, Task<TOutput>> (
83 this, messageQueue, compHelper, () => outgoing.IsCompleted,
84 AsyncTransformProcess, AsyncProcessFinishedTask, () => outgoing.Complete (),
85 dataflowBlockOptions);
86 this.outgoing = new OutgoingQueue<TOutput> (this, compHelper,
87 () => messageQueue.IsCompleted, messageBox.DecreaseCount,
88 dataflowBlockOptions);
91 DataflowMessageStatus ITargetBlock<TInput>.OfferMessage (
92 DataflowMessageHeader messageHeader, TInput messageValue,
93 ISourceBlock<TInput> source, bool consumeToAccept)
95 return messageBox.OfferMessage (messageHeader, messageValue, source, consumeToAccept);
98 public IDisposable LinkTo (ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
100 return outgoing.AddTarget (target, linkOptions);
103 TOutput ISourceBlock<TOutput>.ConsumeMessage (
104 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target,
105 out bool messageConsumed)
107 return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
110 void ISourceBlock<TOutput>.ReleaseReservation (
111 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
113 outgoing.ReleaseReservation (messageHeader, target);
116 bool ISourceBlock<TOutput>.ReserveMessage (
117 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
119 return outgoing.ReserveMessage (messageHeader, target);
122 public bool TryReceive (Predicate<TOutput> filter, out TOutput item)
124 return outgoing.TryReceive (filter, out item);
127 public bool TryReceiveAll (out IList<TOutput> items)
129 return outgoing.TryReceiveAll (out items);
133 /// Transforms one item from the queue if the transform delegate is synchronous.
135 /// <returns>Returns whether an item was processed. Returns <c>false</c> if the queue is empty.</returns>
136 bool TransformProcess ()
140 var dequeued = messageQueue.TryTake (out input);
142 outgoing.AddData (transform (input));
148 /// Processes one item from the queue if the transform delegate is asynchronous.
150 /// <param name="task">The Task that was returned by the synchronous part of the delegate.</param>
151 /// <returns>Returns whether an item was processed. Returns <c>false</c> if the queue was empty.</returns>
152 bool AsyncTransformProcess (out Task<TOutput> task)
156 var dequeued = messageQueue.TryTake (out input);
158 task = asyncTransform (input);
166 /// Process result of finished asynchronous transformation.
168 void AsyncProcessFinishedTask (Task<TOutput> task)
170 if (task == null || task.IsCanceled)
171 messageBox.DecreaseCount ();
173 outgoing.AddData (task.Result);
176 public void Complete ()
178 messageBox.Complete ();
181 void IDataflowBlock.Fault (Exception exception)
183 compHelper.RequestFault (exception);
186 public Task Completion {
187 get { return compHelper.Completion; }
190 public int OutputCount {
191 get { return outgoing.Count; }
194 public int InputCount {
195 get { return messageQueue.Count; }
198 public override string ToString ()
200 return NameHelper.GetName (this, dataflowBlockOptions);