1 // TransformManyBlock.cs
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 TransformManyBlock<TInput, TOutput> :
29 IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput> {
30 readonly CompletionHelper compHelper;
31 readonly BlockingCollection<TInput> messageQueue = new BlockingCollection<TInput> ();
32 readonly MessageBox<TInput> messageBox;
33 readonly ExecutionDataflowBlockOptions dataflowBlockOptions;
34 readonly Func<TInput, IEnumerable<TOutput>> transform;
35 readonly Func<TInput, Task<IEnumerable<TOutput>>> asyncTransform;
36 readonly OutgoingQueue<TOutput> outgoing;
38 TransformManyBlock (ExecutionDataflowBlockOptions dataflowBlockOptions)
40 if (dataflowBlockOptions == null)
41 throw new ArgumentNullException ("dataflowBlockOptions");
43 this.dataflowBlockOptions = dataflowBlockOptions;
44 this.compHelper = new CompletionHelper (dataflowBlockOptions);
47 public TransformManyBlock (Func<TInput, IEnumerable<TOutput>> transform)
48 : this (transform, ExecutionDataflowBlockOptions.Default)
52 public TransformManyBlock (Func<TInput, IEnumerable<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> (this, messageQueue, compHelper,
61 () => outgoing.IsCompleted, TransformProcess, () => outgoing.Complete (),
62 dataflowBlockOptions);
63 this.outgoing = new OutgoingQueue<TOutput> (this, compHelper,
64 () => messageQueue.IsCompleted, messageBox.DecreaseCount,
65 dataflowBlockOptions);
68 public TransformManyBlock (Func<TInput, Task<IEnumerable<TOutput>>> transform)
69 : this (transform, ExecutionDataflowBlockOptions.Default)
73 public TransformManyBlock (Func<TInput, Task<IEnumerable<TOutput>>> transform,
74 ExecutionDataflowBlockOptions dataflowBlockOptions)
75 : this (dataflowBlockOptions)
77 if (transform == null)
78 throw new ArgumentNullException ("transform");
80 this.asyncTransform = transform;
81 this.messageBox = new AsyncExecutingMessageBox<TInput, Task<IEnumerable<TOutput>>> (this, messageQueue, compHelper,
82 () => outgoing.IsCompleted, AsyncTransformProcess, ProcessFinishedTask, () => outgoing.Complete (),
83 dataflowBlockOptions);
84 this.outgoing = new OutgoingQueue<TOutput> (this, compHelper,
85 () => messageQueue.IsCompleted, messageBox.DecreaseCount,
86 dataflowBlockOptions);
89 DataflowMessageStatus ITargetBlock<TInput>.OfferMessage (
90 DataflowMessageHeader messageHeader, TInput messageValue,
91 ISourceBlock<TInput> source, bool consumeToAccept)
93 return messageBox.OfferMessage (messageHeader, messageValue, source, consumeToAccept);
96 public IDisposable LinkTo (ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
98 return outgoing.AddTarget (target, linkOptions);
101 TOutput ISourceBlock<TOutput>.ConsumeMessage (
102 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target,
103 out bool messageConsumed)
105 return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
108 void ISourceBlock<TOutput>.ReleaseReservation (
109 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
111 outgoing.ReleaseReservation (messageHeader, target);
114 bool ISourceBlock<TOutput>.ReserveMessage (
115 DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
117 return outgoing.ReserveMessage (messageHeader, target);
120 public bool TryReceive (Predicate<TOutput> filter, out TOutput item)
122 return outgoing.TryReceive (filter, out item);
125 public bool TryReceiveAll (out IList<TOutput> items)
127 return outgoing.TryReceiveAll (out items);
131 /// Transforms one item from the queue if the transform delegate is synchronous.
133 /// <returns>Returns whether an item was processed. Returns <c>false</c> if the queue is empty.</returns>
134 bool TransformProcess ()
138 var dequeued = messageQueue.TryTake (out input);
140 var result = transform (input);
142 EnqueueTransformed (result);
149 /// Adds the transformed collection to the output queue.
151 void EnqueueTransformed (IEnumerable<TOutput> transformed)
154 if (transformed != null) {
155 foreach (var item in transformed) {
159 messageBox.IncreaseCount ();
160 outgoing.AddData (item);
164 messageBox.DecreaseCount ();
168 /// Processes one item from the queue if the transform delegate is asynchronous.
170 /// <param name="task">The Task that was returned by the synchronous part of the delegate.</param>
171 /// <returns>Returns whether an item was processed. Returns <c>false</c> if the queue was empty.</returns>
172 bool AsyncTransformProcess (out Task<IEnumerable<TOutput>> task)
176 var dequeued = messageQueue.TryTake (out input);
178 task = asyncTransform (input);
186 /// Process result of finished asynchronous transformation.
188 void ProcessFinishedTask (Task<IEnumerable<TOutput>> task)
190 if (task == null || task.IsCanceled)
191 messageBox.DecreaseCount ();
193 EnqueueTransformed (task.Result);
196 public void Complete ()
198 messageBox.Complete ();
201 void IDataflowBlock.Fault (Exception exception)
203 compHelper.RequestFault (exception);
206 public Task Completion {
207 get { return compHelper.Completion; }
210 public int OutputCount {
211 get { return outgoing.Count; }
214 public int InputCount {
215 get { return messageQueue.Count; }
218 public override string ToString ()
220 return NameHelper.GetName (this, dataflowBlockOptions);