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?
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.
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());
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