connection object and GC

  • Thread starter Benjamin Fallar III
  • Start date
B

Benjamin Fallar III

Hi,

I would like to concrete my understanding about my custom object using an
ADO.NET connection object and the behavior of garbage collector.

I have a simple .NET object

public class DBACCESS
{
public void OpenConnection()
{
SqlConnection cn = new SqlConnection(connection_string);
// some code here
}
}

Here is my client code;

DBACCESS db1 = new DBACCESS();
db1.OpenConnection();
db1 = null;

Now, I would like to confirm that when the GC collected my db1 object, will
it also close/release the connection object used by the object instantiated
by my client code (which is the db1)?

Thanks!
 
S

Sahil Malik [MVP]

The answer is YES - but don't use this approach.

When the GC cleans your db1 object, the cn object is also cleaned/closed.
Also, setting db1= null doesn't mean that right at that very moment GC is
going to clean and close your physical connection. As a matter of fact, "cn"
is ready to be GC'ed soon as db1.OpenConnection() executes - because "cn"
has fallen out of scope - but it might be a while before GC gets to it.

But DONOT rely on this mechanism. Because, GC acts on memory pressure. "cn"
will keep an open physical connection open, which the GC won't take into
consideration in the cleanup efforts. Instead you should explicity close and
dispose the "cn" object.

In other words, donot rely on GC to close your connections for you.

- Sahil Malik [MVP]
http://codebetter.com/blogs/sahil.malik/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top