IDbConnection.CreateCommand Question

  • Thread starter Thread starter Benton
  • Start date Start date
B

Benton

Hi there,

If, inside a using (connectionObject) { } block I create commands from the
connection object with its CreateCommand method, will this commands be
disposed when the code exits the using block and the connection gets thus
disposed there?

Thanks in advance,

-Benton
 
Disposable objects need to individually disposed unless otherwise specified
by the container.

The OdbcConnection & OleDbConnection do track their commands & readers with
a WeakReference allowing GC to occur if the user no longer maintains a
reference or if to actively shut them down if connection is closed. It is
still best to actively Dispose the commands and readers to release their
resources as quickly as possible.

using(OleDbConnection connection = new OleDbConnection(connectionstring)) {
connection.Open();
using(OleDbTransaction transaction = connection.BeginTransaction()) {
using(OleDbCommand command = connection.CreateCommand()) {
command.Transaction = transaction();
using(OleDbDataReader reader = command.ExecuteReader()) {
do {
while (reader.Read()) {
}
} while(reader.NextResult());
}
}
transaction.Commit(); // if an exception was thrown,
transaction.Dispose will do the rollback
}
}
 
Back
Top