Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 462
Ignacio Soler Garcia Avatar asked Feb 22 '12 17:02

Ignacio Soler Garcia


People also ask

How do you continue parallel in ForEach?

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.


1 Answers

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?

like image 71
Jon Skeet Avatar answered Oct 04 '22 23:10

Jon Skeet