我有用C#编写的命令行实用程序,它更新了数据库中的一些记录,然后进入循环检查其他一些东西。出于某种原因,在SQL执行后,SQL执行总是在SQL Server 2008中留下休眠等待命令会话。我可以使用SQL服务器活动监视器并运行sp_who2来确认。但SQL事务确实已成功提交。我可以通过代码中的调试以及数据库中数据记录的时间戳来说明这一点。 此外,当我明确停止命令行实用程序时,将打开打开的睡眠会话。这似乎表明我的函数创建了一些SQL连接对象,在应用程序中止时它被CLR垃圾收集之前无法处理。怎么会发生这种情况?谢谢。这是代码:
bool result = false;
using (SqlConnection conn = new SqlConnection(this.Connection))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
@"if not exists (select id from pl where sj=@sj and ej=@ej and dateInactivated is null)
insert into pl(sj,ej,pf, br, tk, lastModified )
values(@sj,@ej,@pf,@br,@tk,getDate())
else
update pl set sj=@sj,ej=@ej,pf=@pf,br=@br,tk=@tk,lastModified=getDate()
where sj=@sj and ej=@ej and dateInactivated is null
";
cmd.Parameters.AddWithValue("@sj", sj);
cmd.Parameters.AddWithValue("@ej", ej);
cmd.Parameters.AddWithValue("@pf", pf);
cmd.Parameters.AddWithValue("@br", br);
cmd.Parameters.AddWithValue("@tk", tkData);
cmd.CommandTimeout = 60;
SqlTransaction trans = null;
try
{
conn.Open();
trans = conn.BeginTransaction();
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
trans.Commit();
conn.Close();
result = true;
}
catch (SqlException ex)
{
if (trans != null)
{
trans.Rollback();
}
Log.WriteLog(LogLevel.ERROR, ex.Message);
result = false;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
}
return result;
请注意,tk字段是xml数据库字段。
答案 0 :(得分:6)
这称为连接池,you want it to work this way。
基本上,完全删除连接,然后为您的应用程序重新建立连接会产生更高的损失,而不仅仅是重新使用上次调用代码时留下的空闲连接。这是一件好事。
答案 1 :(得分:3)
这是由于汇集。 99.99%的时间,这是一件好事 - 它可以减少连接的数量和拆卸,如果多线程可以减少同时打开的连接数。
如果将Pooling=false
添加到连接字符串,则不会使用它。关于这样做的唯一原因是:
第二种非常罕见。第一个应该非常罕见 - 再次强调临时。