Reputation: 2189
I have defined an array of Action<string, int, double, double>
and want to execute them in parallel using Parallel.Invoke()
. Is there any way I can cast my Action's to parameterless Actions so that I can do this or is there another way?
Upvotes: 6
Views: 8361
Reputation: 1902
You could try this:
Parallel.Invoke(() =>
{
YourFirstAction(param1, param2, param3, param4);
}, // close first Action
() =>
{
YourSecondAction(param1, param2, param3, param4);
}//close second Action
); //close parallel.invoke
Upvotes: 7
Reputation: 79
I'm confused as to why the Actions have parameters if you're okay with executing them without sending parameter values. It'd probably be best to use Parallel.ForEach with default values:
Action<string, int, double, double>[] actions;
// Action array, actions, set somewhere in code.
Parallel.ForEach(actions, action => action(string.Empty, 0, 0, 0));
If you want to send parameters then replace the values as you see fit.
I used the following Actions for my tests:
Parallel.For(0, actions.Length, index => actions[index] = (s, i, d1, d2) => Thread.Sleep(100));
Parallel.For(0, parameterless.Length, index => parameterless[index] = () => Thread.Sleep(100));
The results for an array of length 20 in seconds:
Parallel.Invoke: 0.3000709
Parallel.ForEach: 0.3022143
Regular for loop: 2.0000706
So Parallel.Invoke does have the advantage of using parameter-less Actions, which does slightly effect performance, but not by much.
Just for kicks, I tested the parameter-less Action array using Parallel.ForEach and the result was just about the same as the Parallel.Invoke with a result of 0.300979 seconds.
Upvotes: 2