closing connection

  • Thread starter Thread starter Zeng
  • Start date Start date
Z

Zeng

Is there any advantage of always calling SqlConnection's Close method after
done using it vs. just let it go out of scope open and hope the garbage
collection will take care of it?

thanks!
 
Zeng said:
Is there any advantage of always calling SqlConnection's Close method after
done using it vs. just let it go out of scope open and hope the garbage
collection will take care of it?

Absolutely! Calling Close (or Dispose, which is easier to do in C# -
just use a using statement) means the physical connection is returned
to the pool, ready to be used again.

If you don't do that, you could end up running out of pooled
connections if you do lots of requests without generating much data.
 
Is there any advantage of always calling SqlConnection's Close method
after
done using it vs. just let it go out of scope open and hope the garbage
collection will take care of it?

Unlike ADO, ADO.NET requires manual closing of database connections as soon
as they are no longer needed. They are not closed automatically as soon as
they drop out of scope, nor will the garbage collector automatically dispose
them straightaway. Therefore, it is absolutely vital to close connection
objects as soon as possible.
 
exception:

Using a DataAdaptor.Fill method with a closed connection will automatically
open, fill and then close the connection. If the connection is open when the
Fill method is called, it will remain open and you must close it. All the
same goes for the Update method.

-Andrew
 
Back
Top