Use of destructor in c#?

2019-04-07 10:21发布

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 ?

6条回答
倾城 Initia
2楼-- · 2019-04-07 10:49

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-07 10:52

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.

查看更多
何必那么认真
4楼-- · 2019-04-07 10:55

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楼-- · 2019-04-07 11:07

Everybody thinks about garbage collection the wrong way:

A correctly-written program cannot assume that finalizers will ever run.

查看更多
贪生不怕死
6楼-- · 2019-04-07 11:10

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

查看更多
爷、活的狠高调
7楼-- · 2019-04-07 11:11

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.

查看更多
登录 后发表回答