1 // BatchedJoinBlock.cs
3 // Copyright (c) 2012 Petr Onderka
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
23 using System.Collections.Generic;
25 namespace System.Threading.Tasks.Dataflow {
26 public sealed class BatchedJoinBlock<T1, T2> :
27 IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>>> {
28 readonly GroupingDataflowBlockOptions options;
30 readonly CompletionHelper completionHelper;
31 readonly OutgoingQueue<Tuple<IList<T1>, IList<T2>>> outgoing;
34 readonly JoinTarget<T1> target1;
35 readonly JoinTarget<T2> target2;
39 SpinLock batchCountLock;
41 public BatchedJoinBlock (int batchSize)
42 : this (batchSize, GroupingDataflowBlockOptions.Default)
46 public BatchedJoinBlock (int batchSize,
47 GroupingDataflowBlockOptions dataflowBlockOptions)
50 throw new ArgumentOutOfRangeException (
51 "batchSize", batchSize, "The batchSize must be positive.");
52 if (dataflowBlockOptions == null)
53 throw new ArgumentNullException ("dataflowBlockOptions");
54 if (!dataflowBlockOptions.Greedy)
55 throw new ArgumentException (
56 "Greedy must be true for this dataflow block.", "dataflowBlockOptions");
57 if (dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded)
58 throw new ArgumentException (
59 "BoundedCapacity must be Unbounded or -1 for this dataflow block.",
60 "dataflowBlockOptions");
62 BatchSize = batchSize;
63 options = dataflowBlockOptions;
64 completionHelper = CompletionHelper.GetNew (dataflowBlockOptions);
66 target1 = new JoinTarget<T1> (
67 this, SignalTarget, completionHelper, () => outgoing.IsCompleted,
68 dataflowBlockOptions, true, TryAdd);
69 target2 = new JoinTarget<T2> (
70 this, SignalTarget, completionHelper, () => outgoing.IsCompleted,
71 dataflowBlockOptions, true, TryAdd);
73 outgoing = new OutgoingQueue<Tuple<IList<T1>, IList<T2>>> (
74 this, completionHelper,
75 () => target1.Buffer.IsCompleted || target2.Buffer.IsCompleted,
78 target1.DecreaseCount ();
79 target2.DecreaseCount ();
83 public int BatchSize { get; private set; }
85 public ITargetBlock<T1> Target1 {
86 get { return target1; }
89 public ITargetBlock<T2> Target2 {
90 get { return target2; }
95 bool lockTaken = false;
97 batchCountLock.Enter (ref lockTaken);
99 if (options.MaxNumberOfGroups != -1
100 && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
107 batchCountLock.Exit();
113 bool lockTaken = false;
115 batchCountLock.Enter (ref lockTaken);
117 if (batchCount < BatchSize)
120 batchCount -= BatchSize;
124 batchCountLock.Exit();
127 MakeBatch (BatchSize);
130 void MakeBatch (int batchSize)
135 var list1 = new List<T1> ();
136 var list2 = new List<T2> ();
138 // lock is necessary here to make sure items are in the correct order
141 batchLock.Enter (ref taken);
146 while (i < batchSize && target1.Buffer.TryTake (out item1)) {
152 while (i < batchSize && target2.Buffer.TryTake (out item2)) {
158 throw new InvalidOperationException("Unexpected count of items.");
164 var batch = Tuple.Create<IList<T1>, IList<T2>> (list1, list2);
166 outgoing.AddData (batch);
168 VerifyMaxNumberOfGroups ();
171 void VerifyMaxNumberOfGroups ()
173 if (options.MaxNumberOfGroups == -1)
178 bool lockTaken = false;
180 batchCountLock.Enter (ref lockTaken);
182 shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
185 batchCountLock.Exit ();
192 public Task Completion {
193 get { return completionHelper.Completion; }
196 public void Complete ()
200 MakeBatch (batchCount);
201 outgoing.Complete ();
204 void IDataflowBlock.Fault (Exception exception)
206 completionHelper.RequestFault (exception);
209 Tuple<IList<T1>, IList<T2>> ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ConsumeMessage (
210 DataflowMessageHeader messageHeader,
211 ITargetBlock<Tuple<IList<T1>, IList<T2>>> target,
212 out bool messageConsumed)
214 return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
217 public IDisposable LinkTo (ITargetBlock<Tuple<IList<T1>, IList<T2>>> target,
218 DataflowLinkOptions linkOptions)
220 return outgoing.AddTarget(target, linkOptions);
223 void ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReleaseReservation (
224 DataflowMessageHeader messageHeader,
225 ITargetBlock<Tuple<IList<T1>, IList<T2>>> target)
227 outgoing.ReleaseReservation (messageHeader, target);
230 bool ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReserveMessage (
231 DataflowMessageHeader messageHeader,
232 ITargetBlock<Tuple<IList<T1>, IList<T2>>> target)
234 return outgoing.ReserveMessage (messageHeader, target);
237 public bool TryReceive (Predicate<Tuple<IList<T1>, IList<T2>>> filter,
238 out Tuple<IList<T1>, IList<T2>> item)
240 return outgoing.TryReceive (filter, out item);
243 public bool TryReceiveAll (out IList<Tuple<IList<T1>, IList<T2>>> items)
245 return outgoing.TryReceiveAll (out items);
248 public int OutputCount {
249 get { return outgoing.Count; }
252 public override string ToString ()
254 return NameHelper.GetName (this, options);