I have a doubt with threading data service calls within a foreach loop. Here it goes:
Say you need to request data from a service and then process that data, for this example, let's say data request takes 2 seconds and data processing takes another one. If you had to process a list of 10000 elements how would you do it?
The thing I tried was:
Dictionary<int,Task<DataResponse>> d_tasks = Dictionary<int,Task<DataResponse>>();
for(int i=0;i<listOfElements;i++)
{
if(i=0)
//create and run task for first element, save it for latter use in d_tasks
if(not last item)
//create and run task for next element, save it for latter use in d_tasks
if(i>0)
//clean task data from previous element (clean d_tasks)
d_tasks[listOfElements[i].Wait();
DoWorkWithData(d_tasks[listOfElements[i].Result);
}
this way I was able to reduce the time in the loop, since I was able to use the latency from the service to process data.
So here is the final question, is this ok? am I forgetting something? is there some kind of pattern for this kind of situations?
Any help is appreciated.