I am new to threaded programming. I have to run few tasks in PARALLEL and in Background (so that main UI execution thread remain responsive to user actions) and wait for each one of them to complete before proceeding further execution.
Something like:
foreach(MyTask t in myTasks)
{
t.DoSomethinginBackground(); // There could be n number of task, to save
// processing time I wish to run each of them
// in parallel
}
// Wait till all tasks complete doing something parallel in background
Console.Write("All tasks Completed. Now we can do further processing");
I understand that there could be several ways to achieve this. But I am looking for the best solution to implement in .Net 4.0 (C#).
You can use
Task
library to complete:To avoid locking UI Thread, you can use
ContinueWhenAll
in .NET 4.0:If you are in the latest version of .NET, you can use
Task.WhenAll
insteadCheck the below link
.net 4.0 multithreaded parallel programming
To me it would seem like you want
Parallel.ForEach
You can also perform multiple tasks within a single loop
In order for the main UI thread to remain responsive, you will want to use a
BackgroundWorker
and subscribe to itsDoWork
andRunWorkerCompleted
events and then callIf you use Net 4.0 or up, refer to the Parallel class and Task class. Joseph Albahari wrote very clear book about that: http://www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks