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.
A simple 3.5 implementation could look like this
List<TResult> results = new List<TResults>();
List<Func<T, TResult>> tasks = PopulateTasks();
ManualResetEvent waitHandle = new ManualResetEvent(false);
void RunTasks()
{
int i = 0;
foreach(var task in tasks)
{
int captured = i++;
ThreadPool.QueueUserWorkItem(state => RunTask(task, captured))
}
waitHandle.WaitOne();
Console.WriteLine("All tasks completed and results populated");
}
private int counter;
private readonly object listLock = new object();
void RunTask(Func<T, TResult> task, int index)
{
var res = task(...); //You haven't specified where the parameter comes from
lock (listLock )
{
results[index] = res;
}
if (InterLocked.Increment(ref counter) == tasks.Count)
waitHandle.Set();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With