连接当前状态为连接错误消息
本文关键字:连接 错误 消息 状态 | 更新日期: 2023-09-27 18:29:11
我一直随机得到这个错误:
System.Web.Services.Protocols.SoapException:System.Web.Services.protols.Soap Exception:服务器无法处理请求。--->System.InvalidOperationException:连接未关闭。连接的当前状态为正在连接。
它所包含的代码如下:
DataSet ds = new DataSet();
cn = new SqlConnection(GetDBConnectionString());
using (cn)
{
try
{
SqlCommand cmd = new SqlCommand("uspGetNavigationItems", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds, "NavItems");
}
catch (Exception ex)
{
ds = null;
throw ex;
}
finally
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
}
}
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
return ds.Tables[0];
}
else
{
return null;
}
}
else
{
return null;
}
我不明白问题出在哪里,为什么它说连接正在连接,而我终于要清理它了。是因为我正在使用Finally和using语句来关闭它吗?同样,这种情况并不总是随机发生的,这就是为什么我不确定发生了什么
谢谢。
如果使用using-statement
,则不需要最终关闭中的连接,因为它将从dispose
隐含地close
。
经验法则:对实现IDisposable的每个类(如Connections、DataAdapter、Commands)使用using语句。另一方面,DataSet
或DataTable
不实现它,并且不需要手动或通过使用来处理。
但变化:
cn = new SqlConnection(GetDBConnectionString());
using (cn)
{
//code
}
至:
using (var cn = new SqlConnection(GetDBConnectionString()))
{
//code
}
这将被翻译为:
SqlConnection cn = new SqlConnection(GetDBConnectionString());
try
{
//code
}
finally
{
if (cn != null)
((IDisposable)cn).Dispose();
}
旁注:throw
而不是throw ex
将保持堆栈跟踪。使用throw ex
可以隐藏异常的原始来源。
https://stackoverflow.com/a/22628/284240
去掉finally块,因为using
语句将处理连接关闭