简体   繁体   中英

Connection timeout is not always working using Entity Framework

I am using Entity Framework and my connection string looks something like this -

Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;Connection Timeout=2

I have set the connection timeout as 2 sec and most of the time this code works and I got error within 2 sec if the connection is down. But on rare occasions, this timeout happens after 25 to 30 secs as you can see in the below log, the error occurred after 23 secs-

Aug 30 07:13:07 Save begins.

Aug 30 07:13:30 Error - 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.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)

The code is written something like that-

Log.Info("Save begins.")

try{
  Context.SaveChanges();
}
catch(
  Log.Info($"ERROR - + {ex.Message}-{ex.StackTrace}");
)

Log.Info("Save Ends.")

I am not able to find the reason of this delay as it happens very occasionally. Can you please help me to understand what could be the possible reasons of this behavior?

Try to set connection timeout directly to your DbContext class while instantiating it.

var context = new Context("connection string");
(context as IObjectContextAdapter).ObjectContext.CommandTimeout = 2;

After that, try your query again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM