Hello
Yes, GC is smart enough to know that cnn holds a reference to an
SqlConnection and therefore will not collect it until after DoSomething has
finished. The rule is that any object that can be reached by your code is
not eligible for garbage collection. only unreachable objects are.
Your problem will not be that sql connections are getting collected too
early, it will be that they are collected too late. because the garbage
collector only collects objects when it needs to free memory, so the
connection will not be close immediately after DoSomething. And until the
unused connection is collected, the connection to the database will remain
open, and having too many connections open is expensive. For example you can
reach the limit of maximum connections allowed in the connection pool,
license problems or other problems.
To solve this, make sure that the connection is closed after you are
finished using it.
public void DoSomething() {
using(SqlConnec tion cnn = MyClass.MyRepea tedConn()) {
// Do stuff with cnn
}
}
OR
public void DoSomething() {
SqlConnection cnn = MyClass.MyRepea tedConn();
try {
// Do stuff with cnn
}
finally {
cnn.Dispose(); // cnn.Close() will have the same effect
}
}
the two pieces of code above are identical in effect the only difference is
syntax.
Best regards,
Sherif
"C P" <no****@nospam. com> wrote in message
news:#r******** ******@TK2MSFTN GP09.phx.gbl...
I'm coming from Delphi where I have to explicitly create and destroy
instances of objects. I've been working through a C#/ASP.NET book, and
many of the examples repeat the same SqlConnection, SqlDataAdapter etc.
objects, so I thought I'd create a class with a bunch of factory methods to create
my classes for me. But, I'm unclear about how garbage collection works, and
if it is safe to do this. It seems to compile, but am I asking for trouble?
For example:
public class MyClass {
static SqlConnection MyRepeatedConn( ) {
return new SqlConnection(" SomeConnectionS tring");
}
}
public class SomeOtherClass {
public void DoSomething() {
SqlConnection cnn = MyClass.MyRepea tedConn();
// Do stuff with cnn
}
}
At what point will a connection created by MyRepeatedConn( ) be available
to be destroyed? From what (I think) I've read, the connection could be
"garbage collected" as soon as MyRepeatedConn( ) exits (although the
garbage collection will likely happen later on). Am I in danger of my code in
DoSomething() failing, or is the garbage collector smart enough to know
that cnn holds a reference to the SqlConnection in question, and therefore will
leave it alone until DoSomething() has also exited?
Thanks,
Chris