简体   繁体   English

任务并行库ArgumentException

[英]Task Parallel Library ArgumentException

I am attempting to use the Task Parallel Library to build a Matrix cell by cell. 我试图使用任务并行库来按单元格构建Matrix单元格。

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. 我试图做的是并行处理和确定每个单元格,然后一旦完成它们,逐行组装Matrix,其他代码与此示例无关。

The problem I am facing right now is for the following line 我现在面临的问题是以下几行

Task.WaitAll(statusTasks)

I am getting the following ArgumentException 我收到以下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. 我检查了数组,它显示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 . 在基于0的索引语言中使用for循环时,不需要执行< .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] . 由于它<而不是<= ,它已经确保最后一项是campaigns[campaigns.Count - 1]

If you really want to use the TPL, consider using the Parallel class: 如果您真的想使用TPL,请考虑使用Parallel类:

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. 这将使用一个分区程序,它可能决定不为每个j使用一个任务,而是构建分段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM