所以我有一些代码可以连接到数据库,非常标准。
在创建的 DbContext 中,我尝试查询一个表。
当我创建 DbContext 时,我输入了一些不存在的 url,而不是实际的数据库 url。
所以我预计此时会失败,问题是,我不能让它失败的速度超过 30 秒。
我从 System.Data.SqlClient.SqlInternalConnection
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
我尝试创建一个自定义的 DbConfiguration
和 DbExecutionPolicy,但是直到它尝试连接很多次之后才被调用。
public class InternalsDbConfiguration : DbConfiguration
{
public InternalsDbConfiguration()
{
this.SetExecutionStrategy("System.Data.SqlClient", () =>
{
var r = new MyExecutionStrategy();
return r;
});
}
}
public class MyExecutionStrategy : DbExecutionStrategy
{
protected override bool ShouldRetryOn(Exception exception)
{
var s = exception as SqlException;
if (s == null)
return false;
if (s.Number == 53)
return false;
return true;
}
}
我只是不能让连接失败的速度超过 30 秒,因为它一直在经历一些我似乎无法影响的过程,看起来像是一个没有任何后退的重试策略,就像在它放弃并调用我的 MyConnectionStratagy
以弄清楚要做什么之前 15 次。
有什么想法吗?我希望它第一次失败而不是继续尝试。
最佳答案
尝试将 Connection Timeout=5;
添加到连接字符串,如果要为所有后续命令增加,请使用 DbContext.Database.CommandTimeout = 60;
关于c# - EF6 连接需要很长时间才能失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852476/