Skip to main content
 首页 » 编程设计

c#之使 Linq 查询并行运行

2024年02月06日13zfyouxi

我可能有 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... 
} 

请您参考如下方法:

如果您使用 Entity Framework 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.