I am using mvc 5 and follow this example to create an array of Task.
I am sure that the database contains 1 row, at least with a query. I think I have a problem with Task because it threw me an error message
The task argument included a null value.
when i tried:
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);
foreach (var topics in continuation.Result)
{
topics.ForEach(x => list.Add(x));
}
}
I set a breakpoint to validate the array tasks, was tasks[0]not null. It is correctly fixed.
Can you explain to me why?
UPDATE: (based on @YacoubMassad comment)
await Task.WhenAll(tasks);
foreach (var task in tasks)
{
}
UPDATE 2: (based on @DavidPine's answer)
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));
}
}
source
share