I am little bit confused about use of destructor in c#. In my knowledge we can't call destructor acording to my wish it will call automatically before garbage collector for performing some work over class (object) so i want to ask if we are using destructor in c# then whe we need to garbage collector. As i know that destructor can take care of memory then why we need to garbage collector ?
问题:
回答1:
Everybody thinks about garbage collection the wrong way:
A correctly-written program cannot assume that finalizers will ever run.
回答2:
I think based on reading your almost duplicate topic that you don't have a well understanding of how the Garbage Collector works. In a very blunt and brief manner, it is its own service that runs in the background, it tracks and frees memory for unused and disposed objects throughout the entire lifetime of your application. Realistically, you should never have to call the GC yourself, unless in very rare and specific cases.
The desctructors are used to clean up and free unmanaged resources that cannot be freed by the Garbage Collector, see this MSDN page for more information on destructors.
回答3:
It would also be useful to read about the correct way to implement IDisposable pattern. There is much more to it than what we think -
http://msdn.microsoft.com/en-us/magazine/cc163392.aspx
回答4:
The destructor is not for cleaning up managed memory. That is what the garbage collector is for. The destructor is for cleaning up other resources such as handles.
I recommend that you take a look at CLR via C# for details on how this works.
回答5:
I think the confusion here comes from the fact that you can dispose of objects both deterministically and non-deterministically (i.e. when the GC gets round to doing it).
To answer your questions as to why we need a GC at all I would say, even putting aside memory leaks, that GCs are quite performant, and a having a requirement of immediately reclaiming memory might actually lower the total performance of the system. Its a similar argument to the single- vs multi- threaded debate.
回答6:
Destructors in C# should be used very rarely. However, in some cases you have no choice.
For example, if you have a singleton class for logging and from performance reasons you cannot use autoflush, flushing a buffer during finalization of the singleton should be considered.