Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Parallel.Invoke to execute method with parameters

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?

like image 700
phil Avatar asked Apr 22 '12 21:04

phil


People also ask

What method of the parallel class do you use to concurrently execute multiple methods?

The Parallel Invoke method in C# is used to launch multiple tasks that are going to be executed in parallel.

How Parallel Invoke works in c#?

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.

Does parallel invoke wait for completion?

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.

What is parallel for in C#?

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.


2 Answers

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
like image 80
ZeroDotNet Avatar answered Oct 03 '22 18:10

ZeroDotNet


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.

like image 41
thestud2012 Avatar answered Oct 03 '22 20:10

thestud2012