473,473 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Why not destructor?

I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?

--
Regards
Sharon G.
Nov 16 '05 #1
11 2804
Sharon <Sh****@discussions.microsoft.com> wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


I believe you mean destructor, not constructor.

Finalizers (which are what you actually get) aren't called
deterministically - they're called when the GC gets round to it. This
could be much later than you really want, and indeed it may never
happen at all. That's a really bad situation to be in if you need to
free up resources so that something else can use them.

Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
"Sharon" <Sh****@discussions.microsoft.com> wrote in message
news:20**********************************@microsof t.com...
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


Constructor is fine (your message). The problem with destructors (your
subject) is that in .NET you don't know when they will execute, since
objects aren't destroyed when they go out of scope, but when the garbage
collector cleans then up. The Dispose pattern gives you guaranteed execution
when Dispose is called.

Tim
..NET pros and cons
http://www.itwriting.com/phorum/list.php?f=6
Nov 16 '05 #3
There are various problems with the C# 'destructor'.

First, you never know when or if it will be called. So it's not like a C++
destructor, where it gets called the moment the object goes out of scope or
is deleted. It won't be called until a garbage collect occurs. If your
system is not busy right now it could literally be hours before the
destructor runs, even though the object is out of use.

When your application exits, .NET tries to run all finalizers (C#
destructors are really finalizers in disguise), but if it takes more than a
few seconds, it just gives up. So you can never be sure the destructor will
run.

Also, you can't use other finalizable objects from within your destructor.
(I.e. other objects that have destructors.) This is because .NET makes no
guarantees about the order in which it runs finalizers. So it's quite
possible that any objects you were using have already been finalized by the
time your destructor runs. Calling methods on an object whose destructor
has already been run is never a good idea. And since you can't be sure
which ones have been finalized (or indeed which of the objects you are using
even have a finalizer) it's not safe to use objects.

So all of that means that destructors aren't actually a great deal of use.
The main reason for implementing a finalizer is because your object wraps
some kind of raw handle (e.g. a raw Win32 handle, or maybe a handle obtained
through Interop from some unmanaged library) and you need to ensure that it
gets freed. But this is just a safety net, and not a terribly reliable one,
given the limitations mentioned above.
Worse, finalizers cause performance issues. The system has to work harder
to track finalizable objects. Try writing a loop to see how fast you can
create objects without destructors and how fast you can create objects with
destructors - something like this:

int cout = 0;
while (true)
{
new MyClass();
count += 1;
if (count % 10000000 == 0) Console.WriteLine(count);
}

If MyClass does not have a destructor, it creates about 20 million objects a
second on my system. If it does have a destructor, it only manages about 2
million!

Also, finalizers cause objects to hang around in memory very much longer
than they otherwise would, which increases the working set of the process.

So they are best avoided.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

"Sharon" wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?

Nov 16 '05 #4
Jon Skeet wrote:
Finalizers (which are what you actually get) aren't called
deterministically - they're called when the GC gets round to it.
This could be much later than you really want,
and indeed it may never happen at all. In what scenarios do the finalizer get omitted?
Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs. I always define a destructor for my classes.
Is that bad?
If i would not do that, then System.Object::Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object::Finalize(or higher
base class with Finalize overriden) was called.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Sharon <Sh****@discussions.microsoft.com> wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


I believe you mean destructor, not constructor.

Finalizers (which are what you actually get) aren't called
deterministically - they're called when the GC gets round to it. This
could be much later than you really want, and indeed it may never
happen at all. That's a really bad situation to be in if you need to
free up resources so that something else can use them.

Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #5
Great post Ian,

I would just want to add that if you really need a destructor you should
make a rule of implementing the IDisposible interface as well.

While it doesn't take care of the perf issue Ian mentions, it gives the
user of your class a chance to release the external resources before
they remove the root reference to the object. Additionally we could turn
the finalizer off for our object when we know that the dispose method
has been called.

In thoose scenarios I usally conform to the following:

private void Dispose(bool disposing)
{
// release stuff

if ( disposing )
GC.SupressFinilize(this);
}

public void Dispose()
{
this.Dispose(true);
}

~MyClass()
{
this.Dispose(false);
}

--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'

Ian Griffiths [C# MVP] wrote:
There are various problems with the C# 'destructor'.

First, you never know when or if it will be called. So it's not like a C++
destructor, where it gets called the moment the object goes out of scope or
is deleted. It won't be called until a garbage collect occurs. If your
system is not busy right now it could literally be hours before the
destructor runs, even though the object is out of use.

When your application exits, .NET tries to run all finalizers (C#
destructors are really finalizers in disguise), but if it takes more than a
few seconds, it just gives up. So you can never be sure the destructor will
run.

Also, you can't use other finalizable objects from within your destructor.
(I.e. other objects that have destructors.) This is because .NET makes no
guarantees about the order in which it runs finalizers. So it's quite
possible that any objects you were using have already been finalized by the
time your destructor runs. Calling methods on an object whose destructor
has already been run is never a good idea. And since you can't be sure
which ones have been finalized (or indeed which of the objects you are using
even have a finalizer) it's not safe to use objects.

So all of that means that destructors aren't actually a great deal of use.
The main reason for implementing a finalizer is because your object wraps
some kind of raw handle (e.g. a raw Win32 handle, or maybe a handle obtained
through Interop from some unmanaged library) and you need to ensure that it
gets freed. But this is just a safety net, and not a terribly reliable one,
given the limitations mentioned above.
Worse, finalizers cause performance issues. The system has to work harder
to track finalizable objects. Try writing a loop to see how fast you can
create objects without destructors and how fast you can create objects with
destructors - something like this:

int cout = 0;
while (true)
{
new MyClass();
count += 1;
if (count % 10000000 == 0) Console.WriteLine(count);
}

If MyClass does not have a destructor, it creates about 20 million objects a
second on my system. If it does have a destructor, it only manages about 2
million!

Also, finalizers cause objects to hang around in memory very much longer
than they otherwise would, which increases the working set of the process.

So they are best avoided.

Nov 16 '05 #6
If you put GC.SuppressFinalize in your Dispose, and Dispose is called, it does stop the performance issues with finallizers as the GC will not put the object on the finalization queue (and so promote it to Gen1 in the process)

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Great post Ian,

I would just want to add that if you really need a destructor you should
make a rule of implementing the IDisposible interface as well.

While it doesn't take care of the perf issue Ian mentions, it gives the
user of your class a chance to release the external resources before
they remove the root reference to the object. Additionally we could turn
the finalizer off for our object when we know that the dispose method
has been called.

Nov 16 '05 #7
The GC only puts the object on the finalization queue if it's class *overrides* Finalize, or its base class other than System.Object has overridden Finalize. So if you omit it no finalization takes place. So *never* override finalize (implement a destructor) unless you really need it - in other words only if you've got hold of an unmanaged resource via interop that needs freeing should you provide a destructor.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I always define a destructor for my classes.
Is that bad?
If i would not do that, then System.Object::Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object::Finalize(or higher
base class with Finalize overriden) was called.

Nov 16 '05 #8
"Dennis Myrén" wrote:
I always define a destructor for my classes.
Is that bad?
Yes. It means your objects will always survive on the managed heap for far
longer than is necessary. And by extension, so will any objects that your
objects refer to.

If i would not do that, then System.Object::Finalize
would provide the destructor and it would run anyway, would it not?
Actually no. If you don't override the Finalize method, the CLR never calls
it. It knows that System.Object doesn't do anything in its Finalize method,
so it doesn't call it. The only reason Object has a a Finalize method is so
that you can override it.

I thought the destructor was an overridden method from
System.Object, and if it was not overridden, then the
System.Object::Finalize(or higher base class with
Finalize overriden) was called.


Yes it is an overridden method, but no, if it's not overridden then the CLR
knows it doesn't have to call it.

--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #9
Dennis Myrén <de****@oslokb.no> wrote:
Jon Skeet wrote:
Finalizers (which are what you actually get) aren't called
deterministically - they're called when the GC gets round to it.
This could be much later than you really want,
and indeed it may never happen at all. In what scenarios do the finalizer get omitted?


If finalization of all objects is taking too long when a process ends.
Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

I always define a destructor for my classes.
Is that bad?


Yes.
If i would not do that, then System.Object::Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object::Finalize(or higher
base class with Finalize overriden) was called.


object.Finalize doesn't do anything, and the CLR knows this - so it
only puts things which override Finalize onto the finalization queue.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Well yes, from the moment of the Dispose call and forward. But not the
perf issue when creating and maintaining the object before the dispose
method is called.
--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'

Richard Blewett [DevelopMentor] wrote:
If you put GC.SuppressFinalize in your Dispose, and Dispose is called, it does stop the performance issues with finallizers as the GC will not put the object on the finalization queue (and so promote it to Gen1 in the process)

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Great post Ian,

I would just want to add that if you really need a destructor you should
make a rule of implementing the IDisposible interface as well.

While it doesn't take care of the perf issue Ian mentions, it gives the
user of your class a chance to release the external resources before
they remove the root reference to the object. Additionally we could turn
the finalizer off for our object when we know that the dispose method
has been called.

Nov 16 '05 #11
Are you talking about the impact during creation as the runtime puts a reference to the object on the finalizable list? Yes, that is there, but apart from this, there is no overhead in "maintaining" the object as far as I'm aware.

I'm assume you are referring to Chris Brumme's take on this or something similar

http://blogs.msdn.com/cbrumme/archiv.../20/77460.aspx

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<eJ**************@TK2MSFTNGP10.phx.gbl>

Well yes, from the moment of the Dispose call and forward. But not the
perf issue when creating and maintaining the object before the dispose
method is called.
--
Patrik L&ouml;wendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'
Nov 16 '05 #12

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

Similar topics

52
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object...
11
by: Stub | last post by:
Please answer my questions below - thanks! 1. Why "Derived constructor" is called but "Derived destructor" not in Case 1 since object B is new'ed from Derived class? 2. Why "Derived destructor"...
26
by: pmizzi | last post by:
When i compile my program with the -ansi -Wall -pedantic flags, i get this warning: `class vechile' has virtual functions but non-virtual destructor, and the same with my sub-classes. But when i...
11
by: Ken Durden | last post by:
I am in search of a comprehensive methodology of using these two object cleanup approaches to get rid of a number of bugs, unpleasantries, and cleanup-ordering issues we currently have in our...
35
by: Peter Oliphant | last post by:
I'm programming in VS C++.NET 2005 using cli:/pure syntax. In my code I have a class derived from Form that creates an instance of one of my custom classes via gcnew and stores the pointer in a...
14
by: gurry | last post by:
Suppose there's a class A. There's another class called B which looks like this: class B { private: A a; public : B() { a.~A() } }
11
by: AB | last post by:
Hi All, I've got an array of objects, during the execution of the program I'd like to assign a particular object to a certain element in the object array. The sample code's like this... class...
23
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624....
8
by: gw7rib | last post by:
I've been bitten twice now by the same bug, and so I thought I would draw it to people's attention to try to save others the problems I've had. The bug arises when you copy code from a destructor...
7
by: sam | last post by:
Hi, See when i reading a sourcecode of a program, I read that the constructor is ordinary and after that the programmer has written virtual destructor for that constructor . Why we use the...
0
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,...
0
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...
0
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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,...
1
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
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...

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.