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

时间:2018-02-19 12:21:24

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

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

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;

似乎存在竞争条件。

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

1 个答案:

答案 0 :(得分:0)

我修好了。原因是,连接泄漏。在应用程序中还有其他地方,其中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规则是,始终记得使用Transient Life Time作为DBContext。这是每次都有一个新实例,并在使用后立即处理它们。