[英]Connection timeout is not always working using Entity Framework
我正在使用實體框架,我的連接字符串看起來像這樣 -
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;Connection Timeout=2
我已將連接超時設置為 2 秒,並且大多數情況下此代碼都有效,如果連接斷開,我會在 2 秒內出錯。 但在極少數情況下,此超時發生在 25 到 30 秒后,正如您在下面的日志中看到的那樣,錯誤發生在 23 秒后 -
8 月 30 日 07:13:07 保存開始。
8 月 30 日 07:13:30 錯誤 - 與 SQL 服務器建立連接時發生與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。 驗證實例名稱是否正確,並且 SQL 服務器配置為允許遠程連接。 (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)
代碼是這樣寫的——
Log.Info("Save begins.")
try{
Context.SaveChanges();
}
catch(
Log.Info($"ERROR - + {ex.Message}-{ex.StackTrace}");
)
Log.Info("Save Ends.")
我無法找到這種延遲的原因,因為它偶爾會發生。 您能否幫助我了解這種行為的可能原因是什么?
嘗試在實例化時直接將連接超時設置為 DbContext class。
var context = new Context("connection string");
(context as IObjectContextAdapter).ObjectContext.CommandTimeout = 2;
之后,再次嘗試您的查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.