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?
The Parallel Invoke method in C# is used to launch multiple tasks that are going to be executed in parallel.
As I understand it, Parallel. Invoke tries to create 8 threads here - one for each action. So it creates the first thread, runs the first action , and by that gives a ThreadName to the thread. Then it creates the next thread (which gets a different ThreadName ) and so on.
Now, the Parallel. Invoke does not wait for the methods to finish and the spinner is instantly off. Worse, dataX/Y/Z are null and exceptions occur later.
The Parallel. ForEach method splits the work to be done into multiple tasks, one for each item in the collection. Parallel. ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing take place sequentially, while the Parallel.
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
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.
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