1

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,

2 Answers 2

2

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].

Sign up to request clarification or add additional context in comments.

2 Comments

What this means is that there are nulls in the array.
@svick: Exactly. OP is not iterating all the entries, so the task array is not full at the end.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.