James Jeffery
James Jeffery

Reputation: 2101

Parallel Foreach and Actions

I am learning to use Parallel programming and the ForEach method. Is it possible to pass in a list of Actions.

For example, say I have 3 different actions:

I want to create a list of actions (is this possible?) and add one of the actions 50 times. So the list contains 50 elements, each element is one of the above actions.

Now, I want to pass this list into Parallel.Foreach, with MaxDegree set to x (let's say 10 for example sake). So basically it will visit 10 sites at time. I have 4 cores, so I can't imagine this being a problem.

Sorry if that's not making any sense I have no other way to explain how I mean. Is this a suitable way of doing what I want, or is there a better (more canonical) way?

Upvotes: 2

Views: 4552

Answers (4)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

Action<string> action = p =>
{
    VisitSite(p);
};
List<string> sites=new List<string>()
    {"www.Google.com", "www.Yahoo.com", "www.StackOverflow.com",...};
Parallel.ForEach(sites, 
    new ParallelOptions { MaxDegreeOfParallelism = 10 }, action);

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

Yes, you can do it using Action delegates.

Action visitGoogle =        () => { /* ... */ };
Action visitYahoo =         () => { /* ... */ };
Action visitStackOverflow = () => { /* ... */ };
var actionList = new List<Action> { visitGoogle, visitYahoo, visitStackOverflow };

Parallel.ForEach(actionList,
    new ParallelOptions { MaxDegreeOfParallelism = 10 },
    x => x());

Upvotes: 4

StriplingWarrior
StriplingWarrior

Reputation: 156469

Is this possible?

Yes.

Is there a better (more canonical) way?

None that I can think of. This is exactly the sort of thing the Parallel framework was designed for. Since you're creating a list of Actions, you'll probably want to use Parallel.Invoke, though:

List<Action> list = GetActions();
Parallel.Invoke(list.ToArray());

Unless you want to test various concurrency numbers to find the optimal number for this specific purpose, I'd just let the framework decide rather than throwing an arbitrary number (like 10) in there. The framework's pretty smart.

Upvotes: 7

d--b
d--b

Reputation: 5779

Will that do?

List<Action> list;
Parallel.ForEach(list, action => action());

Upvotes: 2

Related Questions