3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
8 // ElementAtQueryOperator.cs
10 // <OWNER>Microsoft</OWNER>
12 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
14 using System.Collections.Generic;
15 using System.Diagnostics.Contracts;
16 using System.Threading;
18 namespace System.Linq.Parallel
21 /// ElementAt just retrieves an element at a specific index. There is some cross-partition
22 /// coordination to force partitions to stop looking once a partition has found the
23 /// sought-after element.
25 /// <typeparam name="TSource"></typeparam>
26 internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
29 private readonly int m_index; // The index that we're looking for.
30 private readonly bool m_prematureMerge = false; // Whether to prematurely merge the input of this operator.
31 private readonly bool m_limitsParallelism = false; // Whether this operator limits parallelism
33 //---------------------------------------------------------------------------------------
34 // Constructs a new instance of the contains search operator.
37 // child - the child tree to enumerate.
38 // index - index we are searching for.
41 internal ElementAtQueryOperator(IEnumerable<TSource> child, int index)
44 Contract.Assert(child != null, "child data source cannot be null");
45 Contract.Assert(index >= 0, "index can't be less than 0");
48 OrdinalIndexState childIndexState = Child.OrdinalIndexState;
49 if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct))
51 m_prematureMerge = true;
52 m_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled;
56 //---------------------------------------------------------------------------------------
57 // Just opens the current operator, including opening the child and wrapping it with
58 // partitions as needed.
61 internal override QueryResults<TSource> Open(
62 QuerySettings settings, bool preferStriping)
64 // We just open the child operator.
65 QueryResults<TSource> childQueryResults = Child.Open(settings, false);
66 return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
69 internal override void WrapPartitionedStream<TKey>(
70 PartitionedStream<TSource,TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
72 // If the child OOP index is not correct, reindex.
73 int partitionCount = inputStream.PartitionCount;
75 PartitionedStream<TSource, int> intKeyStream;
78 intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream();
79 Contract.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexible);
83 intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream;
86 // Create a shared cancelation variable and then return a possibly wrapped new enumerator.
87 Shared<bool> resultFoundFlag = new Shared<bool>(false);
89 PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>(
90 partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
92 for (int i = 0; i < partitionCount; i++)
94 outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], m_index, resultFoundFlag, settings.CancellationState.MergedCancellationToken);
97 recipient.Receive(outputStream);
100 //---------------------------------------------------------------------------------------
101 // Returns an enumerable that represents the query executing sequentially.
104 internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
106 Contract.Assert(false, "This method should never be called as fallback to sequential is handled in Aggregate().");
107 throw new NotSupportedException();
110 //---------------------------------------------------------------------------------------
111 // Whether this operator performs a premature merge that would not be performed in
112 // a similar sequential operation (i.e., in LINQ to Objects).
115 internal override bool LimitsParallelism
117 get { return m_limitsParallelism; }
122 /// Executes the query, either sequentially or in parallel, depending on the query execution mode and
123 /// whether a premature merge was inserted by this ElementAt operator.
125 /// <param name="result">result</param>
126 /// <param name="withDefaultValue">withDefaultValue</param>
127 /// <returns>whether an element with this index exists</returns>
128 internal bool Aggregate(out TSource result, bool withDefaultValue)
130 // If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query
132 if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode.Value != ParallelExecutionMode.ForceParallelism)
134 CancellationState cancelState = SpecifiedQuerySettings.CancellationState;
135 if (withDefaultValue)
137 IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
138 IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
139 result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(m_index);
143 IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken);
144 IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken);
145 result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(m_index);
150 using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered))
154 TSource current = e.Current;
155 Contract.Assert(!e.MoveNext(), "expected enumerator to be empty");
161 result = default(TSource);
166 //---------------------------------------------------------------------------------------
167 // This enumerator performs the search for the element at the specified index.
170 class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int>
172 private QueryOperatorEnumerator<TSource, int> m_source; // The source data.
173 private int m_index; // The index of the element to seek.
174 private Shared<bool> m_resultFoundFlag; // Whether to cancel the operation.
175 private CancellationToken m_cancellationToken;
177 //---------------------------------------------------------------------------------------
178 // Instantiates a new any/all search operator.
181 internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source,
182 int index, Shared<bool> resultFoundFlag,
183 CancellationToken cancellationToken)
185 Contract.Assert(source != null);
186 Contract.Assert(index >= 0);
187 Contract.Assert(resultFoundFlag != null);
191 m_resultFoundFlag = resultFoundFlag;
192 m_cancellationToken = cancellationToken;
195 //---------------------------------------------------------------------------------------
196 // Enumerates the entire input until the element with the specified is found or another
197 // partition has signaled that it found the element.
200 internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
202 // Just walk the enumerator until we've found the element.
204 while (m_source.MoveNext(ref currentElement, ref currentKey))
206 if ((i++ & CancellationState.POLL_INTERVAL) == 0)
207 CancellationState.ThrowIfCanceled(m_cancellationToken);
209 if (m_resultFoundFlag.Value)
211 // Another partition found the element.
215 if (currentKey == m_index)
217 // We have found the element. Cancel other searches and return true.
218 m_resultFoundFlag.Value = true;
226 protected override void Dispose(bool disposing)
228 Contract.Assert(m_source != null);