Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to run three methods in parallel in C#

I have three methods that I call to do some number crunching that are as follows

results.LeftFront.CalcAi();   results.RightFront.CalcAi();   results.RearSuspension.CalcAi(geom, vehDef.Geometry.LTa.TaStiffness, vehDef.Geometry.RTa.TaStiffness); 

Each of the functions is independent of each other and can be computed in parallel with no dead locks.
What is the easiest way to compute these in parallel without the containing method finishing until all three are done?

like image 466
PlTaylor Avatar asked Sep 06 '11 13:09

PlTaylor


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.

Is ForEach parallel?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.


2 Answers

See the TPL documentation. They list this sample:

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork()); 

So in your case this should just work:

Parallel.Invoke(     () => results.LeftFront.CalcAi(),     () => results.RightFront.CalcAi(),     () => results.RearSuspension.CalcAi(geom,                                          vehDef.Geometry.LTa.TaStiffness,                                          vehDef.Geometry.RTa.TaStiffness)); 

EDIT: The call returns after all actions have finished executing. Invoke() is does not guarantee that they will indeed run in parallel, nor does it guarantee the order in which the actions execute.

like image 167
Sander Rijken Avatar answered Sep 28 '22 12:09

Sander Rijken


You can do this with tasks too (nicer if you later need Cancellation or something like results)

var task1 = Task.Factory.StartNew(() => results.LeftFront.CalcAi()); var task2 = Task.Factory.StartNew(() => results.RightFront.CalcAi()); var task3 = Task.Factory.StartNew(() =>results.RearSuspension.CalcAi(geom,                                vehDef.Geometry.LTa.TaStiffness,                                vehDef.Geometry.RTa.TaStiffness));  Task.WaitAll(task1, task2, task3); 
like image 26
Random Dev Avatar answered Sep 28 '22 12:09

Random Dev