473,322 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Starting on C#...

Hi!
We are thinking of doing some performance intensive parts
of our application in C#.
However, I'm a bit concerned about this GC stuff.
From my time as C++ programmer it was pretty easy to
use heavy objects that for instance contain a database conenction
and I could be sure that when the function ended, the connection
object executed a proper disconnect.
So, given class B, I could

int f()
{
B MyConnection;
....
return 0;
}

int c()
{
f();
//Here the database is closed again.
}

And there was no way I could forget anything.
How does this work with C#?
Is the GC only used with objects that are created with new?

Lots of Greetings!
Volker
Apr 25 '06 #1
4 1282
The .Net garbage collector will take care of everything for you.

The exception however is a class which implements the IDisposble
interface. If you use such a class, you have to remember to call
Dispose when you are done with it. That is because IDisposbable
classes usually use COM resources, which can't be garbage collected.
For example, a SqlConnection:

using System.Data.SqlClient;

public static class MyTest {
[STAThread]
public static void Main() {
SqlConnection conn;
string connString;

connString = "Initial Catalog=someDb; Data
Source=localhost;Integrated Security=SSPI"

using( conn = new SqlConnection() ) {
conn.ConnectionString = connString;
conn.Open();

// Do some db stuff
}
}
}

The using block will ensure that, no matter what, Dispose will be
called on the object conn. This will ensure the connection to the
database is closed.

For .Net types which don't implement IDisposable, you can be assured
that the garbage collector will get rid of them (eventually) once all
references to an object have gone out of scope. So you don't need to
worry about the string object in the above code; as soon as the
function exits, connString will be put on the collection list, and the
GC will take care of it later.

HTH
Andy

Apr 25 '06 #2
One more thing...

I agree with everything Andy said in his response but would add that as a
C++ programmer you are probably accustomed to using a destructor for your
class. That is going to be VERY counter-productive in this case, and in fact
will actually cut your performance something like 75%. You shouldn't be
using a destructor unless ABSOLUTELY necessary, which in this case means you
are dealing with UNmanaged resources.

HTH

WhiteWizard (aka Gandalf)
MCSD.NET, MCAD, MCT
"Volker Hetzer" wrote:
Hi!
We are thinking of doing some performance intensive parts
of our application in C#.
However, I'm a bit concerned about this GC stuff.
From my time as C++ programmer it was pretty easy to
use heavy objects that for instance contain a database conenction
and I could be sure that when the function ended, the connection
object executed a proper disconnect.
So, given class B, I could

int f()
{
B MyConnection;
....
return 0;
}

int c()
{
f();
//Here the database is closed again.
}

And there was no way I could forget anything.
How does this work with C#?
Is the GC only used with objects that are created with new?

Lots of Greetings!
Volker

Apr 25 '06 #3
If you want to see an example of how this dispose vs. finalizer stuff is
implemented, look at the System.IO.FileStream object.

FileStream is the object that you use for reading/writing a file. Now you
could let the GC handle everything for you, and just let the filestream
object go out of scope when you are finished with it. However, you will run
into some problems, and that's where IDisposable comes in.

For example, you might have a situation where you need for your FileStream
to realease a file handle immediately, instead of holding onto it until the
GC decides to collect it. This is the same problem that you would run into
in COM if your COM object held onto a file handle until its refcount went to
zero.

On the filestream object, you would call Dispose() or Close() (which calls
Dispose()) to cause the filestream to release the file handle immediately.

You can implement IDisposable on your own classes to give your developers a
way to indicate that the object should release its resources immediately.

As WhiteWizard mentioned, Dispose is a different beast from a Finalizer
(destructor syntax in C#). You only want a finalizer if your object is
holding onto unmanaged resources, such as a Handle, or a DC.

Here's a good article on how the GC works:
http://msdn.microsoft.com/msdnmag/issues/1100/gci/

Here's a good series on using the GC efficiently:
Using the GC Efficiently Part 1:
http://blogs.msdn.com/maoni/archive/...15/156626.aspx
Using the GC Efficiently Part 2:
http://blogs.msdn.com/maoni/archive/...25/234273.aspx
Using the GC Efficiently Part 3:
http://blogs.msdn.com/maoni/archive/...19/327149.aspx
Using the GC Efficiently Part 4:
http://blogs.msdn.com/maoni/archive/...06/415296.aspx
Clearing up some confusion over finalization:
http://blogs.msdn.com/maoni/archive/...04/252697.aspx
"Volker Hetzer" <vo***********@ieee.org> wrote in message
news:e2**********@nntp.fujitsu-siemens.com...
Hi!
We are thinking of doing some performance intensive parts
of our application in C#.
However, I'm a bit concerned about this GC stuff.
From my time as C++ programmer it was pretty easy to
use heavy objects that for instance contain a database conenction
and I could be sure that when the function ended, the connection
object executed a proper disconnect.
So, given class B, I could

int f()
{
B MyConnection;
...
return 0;
}

int c()
{
f();
//Here the database is closed again.
}

And there was no way I could forget anything.
How does this work with C#?
Is the GC only used with objects that are created with new?

Lots of Greetings!
Volker

Apr 25 '06 #4
Andy schrieb:
The .Net garbage collector will take care of everything for you.

The exception however is a class which implements the IDisposble
interface. If you use such a class, you have to remember to call
Dispose when you are done with it. That is because IDisposbable
classes usually use COM resources, which can't be garbage collected. This will be the normal case for me.
For example, a SqlConnection:

using System.Data.SqlClient;

public static class MyTest {
[STAThread]
public static void Main() {
SqlConnection conn;
string connString;

connString = "Initial Catalog=someDb; Data
Source=localhost;Integrated Security=SSPI"

using( conn = new SqlConnection() ) {
conn.ConnectionString = connString;
conn.Open();

// Do some db stuff
}
}
}

The using block will ensure that, no matter what, Dispose will be
called on the object conn. This will ensure the connection to the
database is closed.

Ok, thanks a lot.
I just saw that for this to work with several objects I've got to
nest the using calls but this is something I can live with. (The advantage
is that I can control the order of the dispose calls.)

Lots of Thanks!
Volker
Apr 26 '06 #5

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

Similar topics

12
by: serge calderara | last post by:
Dear all, I have an application which is suppose to start another executable process. As soon as that process is running, I need to retrive its handle. The problem of the particular process I am...
2
by: ceadtinneh | last post by:
Folks, We're implementing a software based mirroring solution. This solution requires that the SQL Server service on the target server be stopped while data is being replicated from the source...
10
by: Andrew Bullock | last post by:
Hi, code: myClass x = new myClass(); x.dosomethingwith(x,y); How do i make dosomethingwith(x,y) run on a separate thread, and then inform the main thread when it has finished?
6
by: Arnie | last post by:
We're using the ServiceController class provided by the .NET Framework, programming in C#. We are using the Start() method to start a service from another service. This works fine most of the...
16
by: Jim Langston | last post by:
I know that functions starting with an underscore, or two underscores, are reserved by the compiler/c++ and should not be used by the user and may cause undefined behavior. My question is, how...
1
by: derik | last post by:
I hav a text file with N number of lines . i am able to read the file till the end .. in between many lines are starting with #. these lines starting with # are to be omitted. pleast help me in...
1
by: sathyan8294 | last post by:
i want to display the name starting with any letter(A-Z,a-z) in textbox from sqldatabase through datagrid using vb.net windows application. for example, values are in datagrid like companyid ...
11
by: Gustaf | last post by:
Some error handling code: catch (System.Xml.XmlException e) { Console.WriteLine("Error in " + e.SourceUri + ": " + e.Message); return; } The output:
1
by: ropo | last post by:
I have a .NET 2.0 app that at one point starts an old MFC App through System.Diagnostics.Process.Start from a model form/ I then wait for it to finish by calling StartedProcess.WaitForExit(); ...
7
by: PaulaCM | last post by:
Hello Again Byters (hmmm... that sounded better in my head!)! Question on Primary Keys / Auto numbering. I want to make sure that each record has its own individual ID (hence primary key) but,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.