使用EF Core dbcontext运行异步选择时出错

时间:2020-06-18 00:34:39

标签: c# asynchronous dbcontext ef-core-3.1

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:'在上一个操作完成之前,第二个操作在此上下文上开始。这通常是由使用相同DbContext实例的不同线程引起的。有关如何避免DbContext线程问题的更多信息,请参见https://go.microsoft.com/fwlink/?linkid=2097913。'

我该如何运行多个任务并消除该错误?

1 个答案:

答案 0 :(得分:0)

最简单的方法是在每个任务中创建一个新的$input = '$data["key1"] = "value1";'; preg_match_all('/\$\w+\["(.*?)"\]\s*=\s*"(.*?)";/', $input, $matches); echo "Match = {" . $matches[1][0] . ", " . $matches[2][0] . "}"; 对象:

Match = {key1, value1}

注意,我做了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); } } 。否则,上下文将在查询完成之前被处理掉。

如果您将其用作负载测试,那很好。请注意,在某些情况下,同时执行1000个任务的执行效果可能会比其他方法差。