0

I have list of methods and need to make parallelize them. How to do that in C#? I see that there is a Parallel namespace?How to use it?

method1()
method2()
method3()
method4()

2 Answers2

5

Parallel.Invoke method:

Parallel.Invoke(
    () => method1(),
    () => method2(),
    () => method3(),
    () => method4()
)

Add namespace System.Threading.Tasks

Backs
  • 24,430
  • 5
  • 58
  • 85
  • It still stuck while invoking them? I don't know why? –  Sep 17 '16 at 10:42
  • @Hanaa `Parallel.Invoke` will wait while all methods complete. If you need run them and go futher use `Task.Run(() => method1())` – Backs Sep 17 '16 at 11:46
  • Please, could you check this? http://stackoverflow.com/questions/39555945/parallelize-minimize-time-reading-number-of-sheets-from-excel-file –  Sep 18 '16 at 09:13
2

You can create a list of Action delegate where each delegate is a call to a given method:

List<Action> actions = new List<Action>
{
     method1,
     method2,
     method3
};

And then use Parallel.ForEach to call them in parallel:

Parallel.ForEach(actions, action => action());
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206