我可能有 40 个 linq 查询,我想并行执行它们。 查询之间没有依赖性,因此并行运行每个查询应该没问题。我想知道如何使下面的代码“更快”/“更好”。
我的两个基本查询和联合:
public override void Filter()
{
var general = (from z in ctx.Interactions
where z.ActivityDate <= EndDate && z.ActivityDate >= StartDate &&
z.Indepth == false && z.Type == InteractionTypes.General
select new { Entries = z.EntryCount }).Sum(x => x.Entries).GetValueOrDefault();
var Indepth = (from z in ctx.Interactions
join program in ctx.Programs on z.Program.Id equals program.Id
where z.ActivityDate <= EndDate && z.ActivityDate >= StartDate && z.Indepth == true && program.Reportable
select z).Count();
...Remaining 38 queries....
AddQuarterlyInfo("# of General Inquiries", "1.1", general);
AddQuarterlyInfo("# of In-Depth Counselling and Information Services Interviews", "1.2", Indepth);
...Union remaining 38 queries...
}
如果您使用实体框架 6,则可以通过执行以下操作来使用异步查询:
var blogs = (from b in db.Blogs
orderby b.Name
select b).ToListAsync();
var blogs2 = (from b in db.Blogs
orderby b.Name
select b).ToListAsync();
var result = await Task.WhenAll(new [] {blogs, blogs2}));
//this is reached when all queries are completed.
这对我有用,尽管如果没有相同的数据源,我无法谈论性能。
int general = 0;
int indepth = 0;
List<Task> queryTasks = new List<Task>
{
new Task(() =>
{
general = (from a in ctx.Interactions
select new {}).Count();
}),
new Task(() =>
{
indepth = (from a in ctx.Interactions
select new {}).Count();
})
};
Parallel.ForEach(queryTasks, q => q.RunSynchronously());
await Task.WhenAll(queryTasks);
AddQuarterlyInfo("# of General Inquiries", "1.1", general);
AddQuarterlyInfo("# of In-Depth Counselling and Information Services Interviews", "1.2", indepth);