【问题标题】:Stress Testing - EntityFramework issue - DBContext Creation压力测试 - EntityFramework 问题 - DBContext 创建
【发布时间】:2018-02-19 12:21:23
【问题描述】:

我正在对 web api (webapi2) 进行压力测试,在 0 秒内有 20 个用户登录。我收到以下错误。

System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.InvalidOperationException: Invalid operation. The connection is closed.

另一个错误

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.

每次创建新的 DBContext 时,我获取 DBContext 的代码:

public static ForcesChecker_Context GetDataContext()
    {           
        return new ForcesChecker_Context();            
    }

对于一个 web api 请求,此代码将被执行多次,并创建此对象的多个实例。当我一次调用 20 个用户时,它会生成 20* ~10 = ~200 个对象。

我的连接字符串:

Min Pool Size=1;Max Pool Size=200;

似乎存在竞争条件。

哪些设置有助于允许更多用户同时访问我的系统?

【问题讨论】:

    标签: entity-framework-6 race-condition stress-testing


    【解决方案1】:

    我修好了。原因是,连接泄漏。应用程序中还有其他地方未正确处理 DBContext 对象。特别是在 UnitOfWork 类中,使用了 DBContext 对象,但没有在 Dispose() 方法中进行处理。这导致了连接泄漏。随后,当新线程(http 请求)尝试使用连接池中的连接时,就会导致竞争条件。这是解决方案代码。

    public class UnitOfWork: IDisposable, IUnitOfWork
    {
        ForcesChecker_Context forcesContext; //EntityFramework DBContext
        ...
        public void Dispose()
        {
              forcesContext.Dispose(); //Leak prevented by this new line.
        }
        ...
    }
    

    Thumb 规则是,始终记住为 DBContext 使用 Transient Life Time。每次都是一个新实例,使用后立即丢弃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2012-03-09
      • 2014-05-31
      • 2011-08-11
      相关资源
      最近更新 更多