c# - 使用using来处置资源

标签 c# .net using-statement

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( )在这种情况下实际上是相同的。它不会立即处理 dacmd,而是等到它们被垃圾回收后释放其资源。

using 的优点是,即使出现异常或提前退出方法(您在方法中间添加 return),您的资源仍然会被释放。方法)。

关于c# - 使用using来处置资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887669/

相关文章:

c# - 关闭一个子窗体会关闭另一个子窗体

c# - 将表单名称转换为c#.net中的表单对象

c# - 无法连接到 MySql 数据库 - "SELECT command denied for user [...]"

c# - 为什么我无法访问通过 POST 请求以编程方式添加的静态文件?

.net - 如何通过 .Net 代码截取网站的屏幕截图?

c# - 如何实现 IEnumerator<T>?

c# - 什么时候应该使用 using 语句?

c# - C# using 语句、SQL 和 SqlConnection

c# - 如何正确使用 'using'命令?

.net - 如何立即释放WPF应用程序中的内存以便它可以反射(reflect)在TaskManager中?