EF6两个上下文与单个上下文有两个等待

时间:2016-03-16 12:57:40

标签: c# performance entity-framework entity-framework-6

哪种方法更适合性能? 注意:对于某些操作,我最多需要执行五个独立查询。

var foo = await context.foos.ToListAsync();
var bar = await context.bars.ToListAsync();

VS

var fooTask = context1.foos.ToListAsync();
var barTask = context2.bars.ToListAsync();
await Task.WhenAll(fooTask , barTask);

在没有等待的情况下使用相同的上下文会很棒,但this answer提及这是不可能的。

1 个答案:

答案 0 :(得分:2)

正如您所知,DbContext不是线程安全的,因此真正并行运行查询的唯一选择是为每个线程/任务创建一个新的DbContext。

创建新DbContext的开销非常低。 https://msdn.microsoft.com/en-us/library/cc853327.aspx

由于该对象来自不同的DbContexts并且为了进一步提高性能,我建议你也使用NoTracking()

编辑:

我使用我拥有的数据库制作了一个简单的测试程序:

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Warming up db context...");

        using (var db = new TestDbContext())
        {
            Console.WriteLine(db.AuditLogItems.ToList().Count);
        }

        // 1st run
        RunAsync();
        RunTasked();

        // 2nd run
        RunAsync();
        RunTasked();

        Console.ReadKey();
    }

    private static void RunAsync()
    {
        Task.Run(async () =>
        {
            var sw = Stopwatch.StartNew();
            List<AuditLogItem> list1;
            List<AuditLogItem> list2;

            using (var db = new TestDbContext())
            {
                list1 = await db.AuditLogItems.AsNoTracking().ToListAsync();
                list2 = await db.AuditLogItems.AsNoTracking().ToListAsync();
            }

            sw.Stop();
            Console.WriteLine("Executed {0} in {1}ms. | {2}", "Async", sw.ElapsedMilliseconds, list1.Count + " " + list2.Count);

        }).Wait();
    }

    private static void RunTasked()
    {
        Func<List<AuditLogItem>> runQuery = () =>
        {
            using (var db = new TestDbContext())
            {
                return db.AuditLogItems.AsNoTracking().ToList();
            }
        };

        var sw = Stopwatch.StartNew();
        var task1 = Task.Run(runQuery);
        var task2 = Task.Run(runQuery);

        Task.WaitAll(task1, task2);

        sw.Stop();
        Console.WriteLine("Executed {0} in {1}ms. | {2}", "Tasked", sw.ElapsedMilliseconds, task1.Result.Count + " " + task2.Result.Count);
    }
}

输出结果为:

Warming up db context...
5908
Executed Async in 293ms. | 5908 5908
Executed Tasked in 56ms. | 5908 5908
Executed Async in 194ms. | 5908 5908
Executed Tasked in 32ms. | 5908 5908

是的,选项2更快......