1

Given below is the sample code.

            string[] str = new string[10];
            str[0] = "A";
            str[1] = "B";
            .... and so on.

            Parallel.Invoke(() =>
            {
                foreach(string temp in str)
                {
                MainFunc(temp);
                }

            });

I want to invoke the "MainFunc" methods 10 times dynamically. Hence, i used foreach loop for. But, the method is running only one time. Please help. Thanks in advance :)

2 Answers2

1

Parallel.Execute executes each of the provided actions, possibly in parallel. In this case you have only one action, so it executes only once.

If you are looking for parallel call to each str then use this.

 Parallel.ForEach(str, (temp) => 
 {
       MainFunc(temp);
 }
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

You usage for Parallel.Invoke is incorrect. This method accepts one or more Actions and executes them in Parrallel. You're sending one Action only, so the 10 iteration executes one after the other. However, your MainFunc should run 10 times (based on the length of the string array.

To Execute the above logic in Parallel, use Parallel.ForEach():

Parallel.ForEach(str, (temp) => MainFunc(temp));
Zein Makki
  • 29,485
  • 6
  • 52
  • 63