473,569 Members | 2,457 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Factory and Garbage Collection

C P
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
Nov 15 '05 #1
2 2108
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

Nov 15 '05 #2
"C P" <no****@nospam. com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
it is safe to do this. It seems to compile, but am I asking for trouble?
The only potential problem I see here is that a SqlConnection must be closed
when you are done with it. By returning the connection from a method like
that you should have it well documented that the receiver is responsible for
closing the connection.
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?
When there are no longer any more reference to it.

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?


An object will not be garbage collected as long as there is a reference to
it.

For example, if you instantiate an object in a method, use it temporarily,
and don't pass it back to the caller or assign it to another reference, then
that object will go out of scope and will be eligible for garbage collection
after the method exits. In your case, you don't have to worry about your
SqlConnection object being collected right away because you passed its
reference, from MyRepeatedConn( ) back to the caller, DoSomething(), who is
holding on to it. Now, since DoSomething() declared cnn, which is a
reference to the new SqlConnection, that SqlConnection object will exist
until DoSomething() exits. If DoSomething assigns the cnn reference to
another reference with a wider scope, then that same SqlConnection object
will exist as long as the reference it is assigned to. If you wanted to
make SqlConnection eligible for garbage collection before it naturally went
out of scope, you would set its reference to null and as long as there
weren't any other references, the garbage collector could collect the
SqlConnection object when it was ready to do so.

Joe
--
http://www.csharp-station.com
Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
810
by: Ganesh | last post by:
Is there a utility by microsoft (or anyone) to force garbage collection in a process without have access to the process code. regards Ganesh
11
2718
by: Rick | last post by:
Hi, My question is.. if Lisp, a 40 year old language supports garbage collection, why didn't the authors of C++ choose garbage collection for this language? Are there fundamental reasons behind this? Is it because C is generally a 'low level' language and they didn't want garbage collection to creep into C++ and ruin everything? Just...
34
6377
by: Ville Voipio | last post by:
I would need to make some high-reliability software running on Linux in an embedded system. Performance (or lack of it) is not an issue, reliability is. The piece of software is rather simple, probably a few hundred lines of code in Python. There is a need to interact with network using the socket module, and then probably a need to do...
5
3579
by: Bob lazarchik | last post by:
Hello: We are considering developing a time critical system in C#. Our tool used in Semiconductor production and we need to be able to take meaurements at precise 10.0 ms intervals( 1000 measurement exactly 10 ms apart. In the future this may decrease to 5ms ). I am concerned that if garbage collection invokes during this time it may...
8
254
by: Craig Buchanan | last post by:
I've seen design patterns for class factories that work well to create (fetch) objects, but I haven't seen anything about how to persist the class' data when it has changed. Is this done thru the factory? What about security? I'm assuming that the factory should enforce security. Has anyone seen examples of this? Thanks, Craig...
8
3026
by: mike2036 | last post by:
For some reason it appears that garbage collection is releasing an object that I'm still using. The object is declared in a module and instantiated within a class that is in turn instantiated by the mainline. The class that instantiated the object in question is definitely still in existence at the point garbage collection swoops in and...
3
3149
by: jimryanabao | last post by:
hello, im trying to solve my problem using factory method but im not sure if im doing it correctly this is my sample code class Base { public: Base(); virtual ~Base; virtual void draw(); };
56
3638
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
158
7738
by: pushpakulkar | last post by:
Hi all, Is garbage collection possible in C++. It doesn't come as part of language support. Is there any specific reason for the same due to the way the language is designed. Or it is discouraged due to some specific reason. If someone can give inputs on the same, it will be of great help. Regards, Pushpa
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7926
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8132
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6286
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5222
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1226
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.