I have a requirement to run a set of heavy functions asynchronously at sametime and populate the results in a list. Here is the pseudo code for this :
List<TResult> results = new List<TResults>();
List<Func<T, TResult>> tasks = PopulateTasks();
foreach(var task in tasks)
{
// Run Logic in question
1. Run each task asynchronously/parallely
2. Put the results in the results list upon each task completion
}
Console.WriteLine("All tasks completed and results populated");
I need the logic inside the foreach
bock. Can you guys plz help me?
I have some constraint : The solution must be .net 3.5 compliant (not .net 4, but a .net 4 alternative solution would be appreciated for my knowledge purpose)
Thanks in advance.
Another variant would be with a small future pattern implementation:
the traditional way is to use a Sempahore. Initialise the semaphore with the number of threads you're using then kick off a thread per task and wait on the semaphore object. When each thread completes, it should increment the semaphore. When the semaphore count reaches 0, the main thread that was waiting will continue.
TPL for 3.5 apparently exists.
Do your processing in separate worker instances, each on their own thread. Use a callback to pass back the results and signal the calling process that the thread is done. Use a Dictionary to keep track of running threads. If you have lots of threads you should load a Queue and launch new threads as old ones finish. In this example all of the threads are created before any are launched to prevent a race condition where the running thread count drops to zero before the final threads are launched.
A simple 3.5 implementation could look like this