[boehm] Put *_freelists into thread_local_freelists (as in BDWGC v7)
[mono.git] / mcs / class / System.Threading.Tasks.Dataflow / System.Threading.Tasks.Dataflow / TransformBlock.cs
1 // TransformBlock.cs
2 //
3 // Copyright (c) 2011 Jérémie "garuma" Laval
4 // Copyright (c) 2012 Petr Onderka
5 //
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:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
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
22 // THE SOFTWARE.
23
24 using System.Collections.Generic;
25 using System.Collections.Concurrent;
26
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;
37
38                 TransformBlock (ExecutionDataflowBlockOptions dataflowBlockOptions)
39                 {
40                         if (dataflowBlockOptions == null)
41                                 throw new ArgumentNullException ("dataflowBlockOptions");
42                 
43                         this.dataflowBlockOptions = dataflowBlockOptions;
44                         this.compHelper = new CompletionHelper (dataflowBlockOptions);
45                 }
46
47                 public TransformBlock (Func<TInput, TOutput> transform)
48                         : this (transform, ExecutionDataflowBlockOptions.Default)
49                 {
50                 }
51
52                 public TransformBlock (Func<TInput, TOutput> transform,
53                                        ExecutionDataflowBlockOptions dataflowBlockOptions)
54                         : this (dataflowBlockOptions)
55                 {
56                         if (transform == null)
57                                 throw new ArgumentNullException("transform");
58
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);
67                 }
68
69                 public TransformBlock(Func<TInput, Task<TOutput>> transform)
70                         : this(transform, ExecutionDataflowBlockOptions.Default)
71                 {
72                 }
73
74                 public TransformBlock (Func<TInput, Task<TOutput>> transform,
75                                        ExecutionDataflowBlockOptions dataflowBlockOptions)
76                         : this (dataflowBlockOptions)
77                 {
78                         if (transform == null)
79                                 throw new ArgumentNullException("transform");
80
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);
89                 }
90
91                 DataflowMessageStatus ITargetBlock<TInput>.OfferMessage (
92                         DataflowMessageHeader messageHeader, TInput messageValue,
93                         ISourceBlock<TInput> source, bool consumeToAccept)
94                 {
95                         return messageBox.OfferMessage (messageHeader, messageValue, source, consumeToAccept);
96                 }
97
98                 public IDisposable LinkTo (ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
99                 {
100                         return outgoing.AddTarget (target, linkOptions);
101                 }
102
103                 TOutput ISourceBlock<TOutput>.ConsumeMessage (
104                         DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target,
105                         out bool messageConsumed)
106                 {
107                         return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
108                 }
109
110                 void ISourceBlock<TOutput>.ReleaseReservation (
111                         DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
112                 {
113                         outgoing.ReleaseReservation (messageHeader, target);
114                 }
115
116                 bool ISourceBlock<TOutput>.ReserveMessage (
117                         DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
118                 {
119                         return outgoing.ReserveMessage (messageHeader, target);
120                 }
121
122                 public bool TryReceive (Predicate<TOutput> filter, out TOutput item)
123                 {
124                         return outgoing.TryReceive (filter, out item);
125                 }
126
127                 public bool TryReceiveAll (out IList<TOutput> items)
128                 {
129                         return outgoing.TryReceiveAll (out items);
130                 }
131
132                 /// <summary>
133                 /// Transforms one item from the queue if the transform delegate is synchronous.
134                 /// </summary>
135                 /// <returns>Returns whether an item was processed. Returns <c>false</c> if the queue is empty.</returns>
136                 bool TransformProcess ()
137                 {
138                         TInput input;
139
140                         var dequeued = messageQueue.TryTake (out input);
141                         if (dequeued)
142                                 outgoing.AddData (transform (input));
143
144                         return dequeued;
145                 }
146
147                 /// <summary>
148                 /// Processes one item from the queue if the transform delegate is asynchronous.
149                 /// </summary>
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)
153                 {
154                         TInput input;
155
156                         var dequeued = messageQueue.TryTake (out input);
157                         if (dequeued)
158                                 task = asyncTransform (input);
159                         else
160                                 task = null;
161
162                         return dequeued;
163                 }
164
165                 /// <summary>
166                 /// Process result of finished asynchronous transformation.
167                 /// </summary>
168                 void AsyncProcessFinishedTask (Task<TOutput> task)
169                 {
170                         if (task == null || task.IsCanceled)
171                                 messageBox.DecreaseCount ();
172                         else
173                                 outgoing.AddData (task.Result);
174                 }
175
176                 public void Complete ()
177                 {
178                         messageBox.Complete ();
179                 }
180
181                 void IDataflowBlock.Fault (Exception exception)
182                 {
183                         compHelper.RequestFault (exception);
184                 }
185
186                 public Task Completion {
187                         get { return compHelper.Completion; }
188                 }
189
190                 public int OutputCount {
191                         get { return outgoing.Count; }
192                 }
193
194                 public int InputCount {
195                         get { return messageQueue.Count; }
196                 }
197
198                 public override string ToString ()
199                 {
200                         return NameHelper.GetName (this, dataflowBlockOptions);
201                 }
202         }
203 }