xes*_*shu 14 c# ado.net garbage-collection using-statement
在我的DAL中,我写这样的查询:
using(SQLConnection conn = "connection string here")
{
SQLCommand cmd = new ("sql query", conn);
// execute it blah blah
}
Run Code Online (Sandbox Code Playgroud)
现在我发现我没有明确关闭SQLCommand对象.现在我知道'using'块将处理SQLConnection对象,但是这还会处理SQLCommand对象吗?如果不是我有一个严重的问题.我必须在SQLCommand上使用'使用'成千上万行代码,或者在数百种方法上执行cmd.Close().请告诉我,如果使用或关闭命令将提供更好的Web应用程序内存管理?
Fre*_*örk 12
在SqlConnection没有关于知识SqlCommand,所以你应该自行关闭:
using (SqlConnection conn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand("sql query", conn))
{
// execute it blah blah
}
Run Code Online (Sandbox Code Playgroud)
不,using声明不会处理命令.
你应该用using语句包装命令,因为这将正确调用Dispose它们:
using(SQLConnection conn = 'connection string here')
{
using(SQLCommand cmd = new ('sql query', conn))
{
//execute it blah blah
}
}
Run Code Online (Sandbox Code Playgroud)
它不会处理SqlCommand,但SqlCommand将最终被垃圾收集处理。我倾向于做以下事情:
using (SqlConn conn ... )
using (SqlComm comm ... )
{
conn.Open();
}
Run Code Online (Sandbox Code Playgroud)
在这里堆叠 using 语句将处理两者。