I can change my loop
for (int i = 0; i < something; i++)
to:
Parallel.For(0, something, i =>
But how to do this with this loop?:
for (i = 3; i <= something / 2; i = i + 2)
Thanks for answers.
I can change my loop
for (int i = 0; i < something; i++)
to:
Parallel.For(0, something, i =>
But how to do this with this loop?:
for (i = 3; i <= something / 2; i = i + 2)
Thanks for answers.
Since
for (int i = 3; i <= something / 2; i = i + 2)
{
...
}
can be rewritten into
for (int k = 1; k < (something + 2) / 4; ++k)
{
int i = 1 + 2 * k;
...
}
you can put
Parallel.For(1, (something + 2) / 4, k =>
{
int i = 1 + 2 * k;
...
});
The third parameter is a delegate
. So every iteration you could specify what your indexing variable shall do inside the delegate.
EDIT: Ok found a working solution:
As already suggested by Dmitry Bychenko you should still start from 0 and just add the startValue
as an offset
int something = 16;
int startValue = 3;
int stepSize = 2;
List<int> numbers = Enumerable.Range(0, 20).ToList();
Parallel.For(0, something / 2, i =>
{
int ind = (stepSize * i) + startValue ; Console.WriteLine(numbers[ind]);
});
Dmitry Bychenko's answer get it but you could also implement your own ParallelFor
with custom step which will make your code somewhat more readable:
static void ParallelFor(int start, int last, Func<int, int> step, Action<int> action)
{
var enumerable = StepEnumerable<int>
.Create(start, step)
.TakeWhile(x => x < last);
Parallel.ForEach(enumerable, action);
}
Here is StepEnumerable
's implementation:
public class StepEnumerator<T> : IEnumerator<T>
{
...
public StepEnumerable(T value, Func<T, T> manipulation)
{
mEnumerator = new StepEnumerator<T>(value, manipulation);
}
public static StepEnumerable<T> Create(T value, Func<T, T> manipulation)
{
return new StepEnumerable<T>(value, manipulation);
}
...
}
public class StepEnumerator<T> : IEnumerator<T>
{
public bool MoveNext()
{
Current = mManipulation(Current);
return true;
}
}
Then, for example, if you run the following code:
ParallelFor(3, 16, x => x + 2, Console.WriteLine);
You'll get the following output (In separate lines of course):
5, 11, 7, 13, 9, 15