How to write Parallel.ForEach with one fixed parameter and another from the collection?

I have a foreach method similar to this:

public void Initialize(ClassB fixed)
{
    foreach (ClassA item in itemCollection)
    {
        this.InitializeStock(fixed, item);
    }
}        

I would like to use Parallel.ForEach with this, but not sure how to do it. I cannot set a fixed parameter as an attribute of a class, since the Initialize method is already called from another Parallel.ForEach.

Thanks in advance.

+5
source share
2 answers

It is not clear what the problem is. This should be good:

public void Initialize(ClassB fixed)
{
    Parallel.ForEach(itemCollection, item =>
    {
        this.InitializeStock(fixed, item);
    });
}

The variable fixedwill be written using the lambda expression so that it can be used in the call InitializeStock.

EDIT: If you really don't need 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, what would you rather read?

+11
source

try the following:

public void Initialize(ClassB fixed)
{
    Parallel.ForEach(itemCollection, new ParallelOptions() { MaxDegreeOfParallelism = 100 },
                (item, i, j) =>
                     {

                         this.InitializeStock(fixed, item);

                     });
}  
0
source

All Articles