Simplest way to run three methods in parallel in C#

Simplest way to run three methods in parallel in C#

Problem:

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?

Solution 1:

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.

Solution 2:

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(new []{taks1, task2, task3});

Documentaion:

In .net 4, Microsoft introduced the Task Parrallel library which was designed to handel this kind of problem, see: http://msdn.microsoft.com/en-us/library/dd460693.aspx

References:

http://stackoverflow.com/questions/7320491/simplest-way-to-run-three-methods-in-parallel-in-c-sharp

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s