压力测试 - EntityFramework 问题 - DBContext 创建

Stress Testing - EntityFramework issue - DBContext Creation

我正在对 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();            
    }

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

我的连接字符串:

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

似乎存在竞争条件。

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

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

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

经验法则是,永远记住为 DBContext 使用瞬态生命周期。即每次都是一个新实例,用完立即销毁。