首页 / C# / c# – tasks参数包含空值
c# – tasks参数包含空值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – tasks参数包含空值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2263字,纯文字阅读大概需要4分钟。
内容图文
![c# – tasks参数包含空值](/upload/InfoBanner/zyjiaocheng/827/e4ef68c2d6ea4f3f87a4ad538ba70124.jpg)
我正在使用mvc 5并按照this sample生成数组任务.
我确定数据库至少包含1行查询.我想我遇到了Task的问题,因为它告诉我错误信息
The tasks argument included a null value.
我试过的时候:
// 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));
}
}
我已设置断点来检查数组任务,任务[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));
}
}
解决方法:
这里有一些问题:
1.使用任务或任务时< T>如果可用的话,总是使用async / await,即;你正在使用.NET 4.5.
2.当您调用Task.WhenAll(tasks)时,数组中的任务可能为null.你需要检查它并正确处理它.
3.你需要等待所有时间以确保工作完成,等待Task.WhenAll(任务).
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 () =>
{
// Isn't it possible that the where clause filters out and returns null?
return await db.Topics
.Where(m => m.Type == type && m.Category == _cg)
.ToListAsync();
});
i++;
}
// Use await keyword to ensure that work is done
var continuation = await Task.WhenAll(tasks.Where(t => t != null).ToArray());
// never go to this loop...
foreach (var topics in continuation.Result)
{
topics.ForEach(x => list.Add(x));
}
}
内容总结
以上是互联网集市为您收集整理的c# – tasks参数包含空值全部内容,希望文章能够帮你解决c# – tasks参数包含空值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。