Possible Duplicate:
Trying to understand the ‘using’ statement better
我确实阅读了所有其他帖子,但没有人真正回答我的问题。
这是我返回表格的函数
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(mainConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}
前一个相对于后一个(我在发现“使用”之前总是使用的那个)的优势是什么:
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(mainConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
对于第二个,con、cmd 和 da 没有正确处理吗? 第二个有什么问题吗?
谢谢!
最佳答案
Is there anything wrong with the second?
只要代码中没有出现异常,con
的工作方式就会相同,因为 Close()
和 Dispose( )
在这种情况下实际上是相同的。它不会立即处理 da
或 cmd
,而是等到它们被垃圾回收后释放其资源。
using
的优点是,即使出现异常或提前退出方法(您在方法中间添加 return
),您的资源仍然会被释放。方法)。
关于c# - 使用using来处置资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887669/