【问题标题】:Use of using to dispose resources [duplicate]使用 using 来处理资源 [重复]
【发布时间】:2012-12-02 23:38:40
【问题描述】:

可能重复:
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 是否正确处理? 第二个有什么问题吗?

谢谢!

【问题讨论】:

  • 连接对象是最重要的关闭或释放对象,因为它拥有物理数据库资源。在第二种情况下,如果出现异常,直到 GC 完成对象后才会关闭。处理命令和数据适配器是一个非常好的主意,但不是那么重要。

标签: c# .net using-statement


【解决方案1】:

优点是using 模式调用IDisposable 接口上的Dispose() 方法,保证您可能错过的任何清理逻辑 得到正确执行,即使出现异常也是如此扔了。

实际上,实现IDisposable 的对象持有非托管 资源,这些资源在调用Dispose() 时会被清理。所以调用Close() 可能还不够。

【讨论】:

    【解决方案2】:

    第二个有什么问题吗?

    只要代码中没有异常,con 的工作方式相同,因为Close()Dispose() 在这种情况下实际上是相同的 .它不会立即处理dacmd,而是等到它们被垃圾回收后释放它们的资源。

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

    【讨论】:

      【解决方案3】:

      不,它们相同。这就是using 的全部

      如果您的代码抛出异常会怎样?在垃圾收集器碰巧处理这些对象之前,这些对象不会被释放。

      【讨论】:

        【解决方案4】:

        在这种情况下,“使用”尝试实现RAII 模式,这在处理有限资源(例如数据库连接)时特别有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-26
          • 2018-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-01
          • 1970-01-01
          相关资源
          最近更新 更多