使用 EF Core dbcontext 运行 async select 时出错

Got error when run async select with EF Core dbcontext

public class Person 
{
    [Key]
    public Guid Id { get; set; }
    public string FullName { get; set; }
}

public class ApplicationDbContext : DbContext 
{
    public DbSet<Person> People { get; set; }
}

public class Program 
{
    public void Main() 
    {
        using var context = new ApplicationDbContext(*configuration here*);
        var doWorks = Enumerable.Range(0, 1000).Select(x => context.People.AsNoTracking().ToArrayAsync());
        await Task.WhenAll(doWorks);
    }
}

我收到这个错误:

System.InvalidOperationException: 'A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.'

我怎样才能 运行 执行这样的多项任务并消除该错误?

最简单的方法是在每个任务中创建一个新的 ApplicationDbContext 对象:

public class Program {
    public void Main() {
        var doWorks = Enumerable.Range(0, 1000).Select(async x => {
                          using var context = new ApplicationDbContext(*configuration here*);
                          await context.People.AsNoTracking().ToArrayAsync();
                      });
        await Task.WhenAll(doWorks);
    }
}

注意我制作了你的 lambda async 并使用了 await。否则,上下文将在查询完成之前被释放。

如果您将此作为负载测试,那很好。请注意,在某些情况下,同时执行 1000 个任务可能比其他方式表现更差。