【发布时间】:2018-04-10 17:06:40
【问题描述】:
我有一个简单的 SQL 语句,我想在短时间内调用很多次(在
System.InvalidOperationException: '超时已过期。在从池中获取连接之前超时时间已过。这可能是因为所有池连接都在使用中并且已达到最大池大小。'
我已经阅读了很多关于这个错误的帖子。他们都建议要么用using 块包装你的代码,要么在最后调用SQL 连接的.Close() 方法。这两个我都实现了,还是不行。我没有正确实施吗? (该方法工作正常,当不重复调用时)。
我的代码如下所示:
public static ObjectModel GetObject(int objGroupId, DateTime date)
{
ObjectModel obj = new ObjectModel () { EffectiveFrom = date };
// Get connection string from the App.Config file
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("[dbo].[GetObjectData]", connection))
{
// Request the data which were in force on the specified date
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = obj.EffectiveFrom;
command.Parameters.Add("@ObjecGrouptId", SqlDbType.Int).Value = objGroupId;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int objId = reader.GetInt32NullIsZero("Id");
decimal value = reader.GetDecimalNullIsZero("value");
SetObjData(obj, objId, value);
}
}
}
connection.Close();
}
return obj;
}
【问题讨论】:
-
这是打开连接的唯一代码吗?
-
这些调用是否重叠?默认的最大池大小为 100。如果您尝试在 parallel 中触发超过 100 个查询,则会收到此错误。你可以碰一下
MaxPoolSize,或者想办法序列化调用。 -
我也建议检查你的存储过程,如果你能优化它的执行时间。
-
@C.Evenhuis 这是每次抛出错误的地方,没有例外。我怀疑它也会从其他方法抛出异常,如果它发生在那里。它被称为其他地方,但应始终包裹在
using块中。 -
@TheGeneral GC 在这里不是一个因素;
using释放到池的 底层 连接;收集SqlConnection对象需要多长时间是无关紧要的
标签: c# .net sql-server