I am attempting to use the Task Parallel Library to build a Matrix cell by cell.
I have the following code that does this:
List<Campaign> campaigns = GetHomeCampaigns();
Dictionary<int, string> sellers = GetHomeSellers();
int numTasks = campaigns.Count*sellers.Count;
Task<MatrixCell<string>>[] statusTasks = new Task<MatrixCell<string>>[numTasks];
int count = 0;
for(int i = 0; i < campaigns.Count -1;i++)
{
for(int j = 0; j < sellers.Count -1;j++)
{
Func<MatrixCell<string>> getStatus = () => GetStatus(campaigns[i].CampaignID, sellers.ElementAt(j).Key);
statusTasks[count] = Task.Factory.StartNew(getStatus);
count++;
}
}
Task.WaitAll(statusTasks);
What I am attempting to do is to process and determine each cell in parallel, and then once they are all completed, assemble the Matrix row by row with additional code that is not relevant to this example.
The problem I am facing right now is for the following line
Task.WaitAll(statusTasks)
I am getting the following ArgumentException
The tasks array included at least one null element.
Parameter name: tasks
I have checked the array, and it shows all the items are present in statusTasks.
Not sure quite where else to look.
Thanks,
When you use a for
loop in a 0-based index language, you don't need to do < .Count - 1
. That should be:
for (int i = 0; i < campaigns.Count; i++)
Since it is <
and not <=
, it already ensures that the last item will be campaigns[campaigns.Count - 1]
.
If you really want to use the TPL, consider using the Parallel class:
Parallel.For(0, campaigns.Count, i => // the outer loop is most important
{
Parallel.For(0, sellers.Count, j =>
{
GetStatus(campaigns[i].CampaignID, sellers.ElementAt(j).Key);
}
}));
// no Waiting here
This will use a Partitioner that will probably decide not to use a Task for every j
but to build segments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.