NET C# using the Stop method. It's not uncommon to break the execution of a for/foreach loop using the 'break' keyword. A for loop can look through a list of integers and if the loop body finds some matching value then the loop can be exited.
For and Parallel. ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops ( For and For Each in Visual Basic); an unhandled exception causes the loop to terminate as soon as all currently running iterations finish.
ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.
The Parallel. ForEach method splits the work to be done into multiple tasks, one for each item in the collection. Parallel. ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing take place sequentially, while the Parallel.
Use the ParallelLoopState.Break
method:
Parallel.ForEach(list,
(i, state) =>
{
state.Break();
});
Or in your case:
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder, ParallelLoopState>((ColorIndexHolder Element, ParallelLoopState state) =>
{
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I)
{
Found = true;
state.Break();
}
}));
You do this by calling using the overload of Parallel.For
or Parallel.ForEach
which passes in a loop state, then calling ParallelLoopState.Break
or ParallelLoopState.Stop
. The main difference is in how quickly things break - with Break()
, the loop will process all items with an earlier "index" than the current. With Stop()
, it will exit as quickly as possible.
For details, see How to: Stop or Break from a Parallel.For Loop.
What you should be using is Any
, rather than a foreach loop:
bool Found = ColorIndex.AsEnumerable().AsParallel()
.Any(Element => Element.StartIndex <= I
&& Element.StartIndex + Element.Length >= I);
Any
is smart enough to stop as soon as it knows that the result must be true.
LoopState is certainly a great answer. I found the previous answers had so much other stuff that it was hard to see the answer, so here is a simple case:
using System.Threading.Tasks;
Parallel.ForEach(SomeTable.Rows(), (row, loopState) =>
{
if (row.Value == testValue)
{
loopState.Stop(); // Stop the ForEach!
}
// else do some other stuff here.
});
Just use the loopState
that can be provided.
Parallel.ForEach<ColorIndexHolder>(ColorIndex.AsEnumerable(),
new Action<ColorIndexHolder>((Element, loopState) => {
if (Element.StartIndex <= I && Element.StartIndex + Element.Length >= I) {
loopState.Stop();
}
}));
Look at this MSDN article for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With