使Linq查询运行并行

时间:2015-03-23 16:34:57

标签: c# linq

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

2 个答案:

答案 0 :(得分:2)

如果您通过执行以下操作来使用实体框架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. 

答案 1 :(得分:2)

这对我有用,虽然如果没有相同的数据源我就无法说话。

    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());

    Task.WaitAll(queryTasks.ToArray());

    AddQuarterlyInfo("# of General Inquiries", "1.1", general);                 
    AddQuarterlyInfo("# of In-Depth Counselling and Information Services Interviews", "1.2", indepth);