Search code examples
c#parallel.invoke

How to add methods dynamically inside a parallel.invoke


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 :)


Solution

  • 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);
     }