I have a foreach method like this one:
public void Initialize(ClassB fixed)
{
foreach (ClassA item in itemCollection)
{
this.InitializeStock(fixed, item);
}
}
I would like to use a Parallel.ForEach with this one but not sure on how to do it. I cannot set the fixed parameter as a class attribute as the Initialize method is already called from another Parallel.ForEach.
Thanks in advance.
ForEach() is meant to be a parallel Asynchronous operation, so there is nothing to continue; or break; as theoretically all _dongles. GetArray() members should be accessed at the same instance, thus having a break; or especially a continue; won't be logical in the first place. You should just use return; that's all.
It's not clear what the problem is. This should be fine:
public void Initialize(ClassB fixed)
{
Parallel.ForEach(itemCollection, item =>
{
this.InitializeStock(fixed, item);
});
}
The fixed
variable will be captured by the lambda expression so that it can be used when calling InitializeStock
.
EDIT: If you really don't want lambda expressions:
private class ClassBHolder
{
private readonly ClassB fixed;
// Foo is the class which has the Initialize method
private readonly Foo container;
internal ClassBHolder(ClassB fixed, Foo container)
{
this.fixed = fixed;
this.container = container;
}
internal void Execute(ClassA item)
{
container.InitializeStock(fixed, item);
}
}
public void Initialize(ClassB fixed)
{
ClassBHolder holder = new ClassBHolder(fixed, this);
Parallel.ForEach(itemCollection, holder.Execute);
}
... but really, which would you rather read?
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