我可以处理DataTable并在以后继续使用它的数据吗?

问题描述:

Noob ADO.NET问题:我可以执行以下操作吗?我可以处理DataTable并在以后继续使用它的数据吗?

  1. 检索一个DataTable莫名其妙。
  2. 处置它。
  3. 仍然使用其数据。 (但不是发回数据库,或者要求数据库进行更新。)

我有以下的功能,这是间接地通过每WebMethod在我的Web服务调用:

public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters) 
{ 
    // Read the connection string from the web.config file. 
    Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores"); 
    ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."]; 

    SqlConnection connection = null; 
    SqlCommand command = null; 
    SqlParameterCollection parameterCollection = null; 
    SqlDataAdapter dataAdapter = null; 
    DataTable dataTable = null; 

    try 
    { 
     // Open a connection to the database. 
     connection = new SqlConnection(connectionString.ConnectionString); 
     connection.Open(); 

     // Specify the stored procedure call and its parameters. 
     command = new SqlCommand(cmdText, connection); 
     command.CommandType = CommandType.StoredProcedure; 
     parameterCollection = command.Parameters; 
     foreach (SqlParameter parameter in parameters) 
      parameterCollection.Add(parameter); 

     // Execute the stored procedure and retrieve the results in a table. 
     dataAdapter = new SqlDataAdapter(command); 
     dataTable = new DataTable(); 
     dataAdapter.Fill(dataTable); 
    } 
    finally 
    { 
     if (connection != null) 
     { 
      if (command != null) 
      { 
       if (dataAdapter != null) 
       { 
        // Here the DataTable gets disposed. 
        if (dataTable != null) 
         dataTable.Dispose(); 
        dataAdapter.Dispose(); 
       } 

       parameterCollection.Clear(); 
       command.Dispose(); 
      } 

      if (connection.State != ConnectionState.Closed) 
       connection.Close(); 
      connection.Dispose(); 
     } 
    } 

    // However, I still return the DataTable 
    // as if nothing had happened. 
    return dataTable; 
} 

的一般规则是什么处置实现IDisposable,是否“需要它”与否。当你需要它的时候,你可以节省时间,而你却没有想到要处置。

对对象调用Dispose之后,就不应该再使用它了。期。它违反了Dispose的整个概念。

这就是为什么你不应该调用Dispose你是从一个方法返回一个对象。当它们完成对象时,将其留给调用者调用Dispose。


顺便说一句,你的代码可能会更简单。更多类似这样的:

using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString)) 
{ 
    connection.Open(); 

    using (SqlCommand command = new SqlCommand(cmdText, connection)) 
    { 
     //... 
     using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command)) 
     { 
      DataTable dataTable = new DataTable(); 
      dataAdapter.Fill(dataTable); 
      return dataTable; 
     } 
    } 
} 
+0

当'using'子句在'try'块内,并且发生异常时,是否正确清理了一次性对象? – pyon 2011-03-04 23:45:05

+0

@Eduardo:是的。一个try块不会改变里面发生的事情。 – 2011-03-05 00:08:22

+0

我的意思是,如果在'using'块内发生异常,在技术上,程序的控制流程不会达到应丢弃一次性对象的地步。 – pyon 2011-03-05 04:40:23

那么,你不能有你的蛋糕,吃它:)

关闭连接等,当然,但为什么你需要处置表?这没有必要。只是按原样返回。

否则你会在一个位置,你...表复制到别的东西,然后返回呢?例如,如果您使用ORM并将数据映射到对象,然后返回对象,这将有意义,但如果不是,则直接使用表/数据集。