超时。在从池中获取连接之前,超时时间已过。
超时。在从池中获取连接之前,超时时间已过。
我正在使用WebApi和AngularJS开发一个应用程序。在使用这个应用程序一段时间后,我遇到了以下异常。在这个应用程序中,我使用了EntityFramework。\n\"超时。在从池中获取连接之前,超时时间已过。可能是因为所有的池连接都在使用中,且已达到最大池大小。\"
\n堆栈跟踪\n
在 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) ↵ 在 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) 在 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) 在 System.Data.SqlClient.SqlConnection.Open() 在 System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
文章标题:解决"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool."问题的方法
在程序开发过程中,有时候我们会遇到"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool."这个错误。下面是解决这个问题的方法:
1. 在finally块中始终关闭连接
2. 增加连接池大小,可以在连接字符串中设置Min Pool Size和Max Pool Size属性
string connectionString = "Data Source=localhost; Initial Catalog=Northwind;Integrated Security=SSPI; Min Pool Size=10; Max Pool Size=100";
3. 如果不需要使用连接池,可以将Pooling属性设置为false
string connectionString = "Data Source=localhost; Initial Catalog=Northwind;Integrated Security=SSPI; Pooling=false;";
注意:在尝试第三种方法时,可能会遇到"Error:Keyword not supported: '&pooling'"错误。
文章标题:解决数据库连接超时问题的方法
最近我遇到了同样的问题。最终,我采用了以下的代码模式来解决这个问题:
using (SqlConnection con = new SqlConnection(strCon)) { using (SqlCommand cmd = new SqlCommand(strCmdText, con)) { con.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { // 进行一些操作 dr.Close(); } } con.Close(); }
这段代码解决了我的问题。其中,`DataReader.Close()` 是解决问题的关键。看来微软应该修改他们的建议,因为我在他们的网站上找到了很多不建议使用 `try { } finally { con.Close(); }` 这种模式的建议。尽管我没有明确尝试过这种模式,因为这种模式在我们整个数据库层中相当普遍,我希望能找到更接近的解决方法。
希望这篇文章能对某些人有所帮助。
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. 这个问题的出现的原因是数据库连接池中没有可用的连接,超时时间已经过去了。
解决方法如下:
1. 关闭数据库连接是非常重要的。
SqlConnection myConnection = new SqlConnection(ConnectionString); try { conn.Open(); someCall (myConnection); } finally { myConnection.Close(); }
或者
using (SqlConnection myConnection = new SqlConnection(ConnectionString)) { myConnection.Open(); someCall(myConnection); }
2. 检查有多少用户连接到数据库以及查询的超时时间。同时检查是否有长时间执行的查询。
此外,以下链接可能也包含了解决该问题的答案:
- [How can I solve a connection pool problem between ASP.NET and SQL Server?](https://stackoverflow.com/questions/670774)
- [When does Entity Framework open and close Database Connections?](https://stackoverflow.com/questions/1282675)
需要注意的是,他没有打开或创建连接;Entity Framework在幕后隐式地进行了这个操作。如果有一个调用`new SqlConnection`的话,那就可以使用`using`或者`.Dispose`来释放连接。