Simplest way to run three methods in parallel in C#
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(task1, task2, task3);
Solution 3
In .NET 4, Microsoft introduced the Task Parallel Library which was designed to handle this kind of problem, see Parallel Programming in the .NET Framework.
Solution 4
To run parallel methods which are independent of each other ThreadPool.QueueUserWorkItem can also be used. Here is the sample method-
public static void ExecuteParallel(params Action[] tasks)
{
// Initialize the reset events to keep track of completed threads
ManualResetEvent[] resetEvents = new ManualResetEvent[tasks.Length];
// Launch each method in it's own thread
for (int i = 0; i < tasks.Length; i++)
{
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>
{
int taskIndex = (int)index;
// Execute the method
tasks[taskIndex]();
// Tell the calling thread that we're done
resetEvents[taskIndex].Set();
}), i);
}
// Wait for all threads to execute
WaitHandle.WaitAll(resetEvents);
}
More detail about this function can be found here:
http://newapputil.blogspot.in/2016/03/running-parallel-tasks-using.html
Related videos on Youtube
PlTaylor
Updated on July 02, 2020Comments
-
PlTaylor almost 4 years
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?-
sll over 12 yearsYou only interested in task parallel lib solution? What about straightforward Delegate.BeginInvoke() or even Thread.Start()?
-
Random Dev over 12 yearshe want to wait for all results - you can do this with what you suggest but have to do the sync by yourself - IMHO you should use Task as long there isn't some really good reason not to do - this will get even more important if C#/async goes live
-
PlTaylor over 12 yearsAll the thread start examples I have found don't wait until the group of functions complete.
-
Random Dev over 12 yearsNo they don't and you should really use the Task-Library for this kind of stuff. IMHO MS is pushing this approach with async and it is really a nice lib (almost as good as F#'s async-workflows :D )
-
-
Jonathan over 12 yearsWill this wait until all Parallel tasks are completed?
-
PlTaylor over 12 yearsFor all the searching I have done, it seems as though most people have left out this simple example. Thanks for the quick response and great answer.
-
Libor almost 11 years@Jonathan It will wait. The construct is similar to starting several tasks and then calling
Task.WaitAll
. -
Microsoft Developer over 9 yearsPossibly not a good idea to use start new see: (blog.stephencleary.com/2013/08/startnew-is-dangerous.html)
-
Random Dev over 9 years@dotNETNinja true now - this answer is quite old (as you can see) - there was no async then - anyhow you can just switch it with
Task.Run
as adviced by the link you provided - given you may use .net4.5 (or newer) -
Ziggler almost 9 yearsI have something similar here.. stackoverflow.com/questions/30261335/…
-
Eli Arbel almost 8 years
Parallel
also uses the current thread to execute actions, so it's not blocking a thread waiting for the actions to be completed. If you have synchronous, CPU-bound operations you need to parallelize, it's a better choice. -
F11 over 4 yearshow to get return values from different methods