【发布时间】:2015-12-19 00:40:28
【问题描述】:
我用的是mvc 5,跟着this sample生成一个数组Task。
我确定数据库至少包含 1 行的查询。我认为我遇到了 Task 的问题,因为它向我抛出了错误消息
tasks 参数包含一个空值。
当我尝试时:
// I'm sure `cg` was not null and `type` was not empty
var cg = new List<string>();
var type = "";
var db = new MyDbContext();
var list = new List<TopicViewModels>();
if (cg != null && cg.Count > 0)
{
var tasks = new Task<List<TopicViewModels>>[13];
byte i = 0;
while (i < cg.Count)
{
string _cg = cg[i];
tasks[i] = Task.Run(async () =>
{
return await db.Topics.Where(m => m.Type == type && m.Category == _cg)
.ToListAsync();
});
i++;
}
var continuation = Task.WhenAll(tasks); //the tasks argument included a null value
// never go to this loop...
foreach (var topics in continuation.Result)
{
topics.ForEach(x => list.Add(x));
}
}
我设置了断点来检查数组tasks,tasks[0] 不为空。它已正确附加。
你能解释一下为什么吗?
更新:(基于@YacoubMassad 评论)
await Task.WhenAll(tasks); //same error here...
//never go to this loop, too...
foreach (var task in tasks)
{
//
}
更新 2:(基于 @DavidPine 的回答)
if (cg != null && cg.Count > 0)
{
var tasks = new List<Task<List<TopicViewModels>>>();
cg.ForEach(x =>
{
tasks.Add(Task.Run(async () =>
{
return await db.Topics.Where(m => m.Type == type && m.Category == x)
.ToListAsync();
}));
});
foreach (var topics in await Task.WhenAll(tasks.ToArray()))
{
topics.ForEach(x => list.Add(x));
}
}
【问题讨论】:
-
这段代码存在的方法是
async吗? -
@YacoubMassad 是的。它在
public async Task<ActionResult> Topics(){} -
尝试将
var continuation = Task.WhenAll(tasks);改为await Task.WhenAll(tasks);,然后循环遍历tasks数组 -
我认为一个问题是
cg.Count可能小于 13 -
@YacoubMassad 我只是再试一次并更新我的问题。请检查