王朝网络
分享
 
 
 

Destructors in C#

王朝c#·作者佚名  2006-01-31
宽屏版  字体: |||超大  

Destructors in C#

By Ansil

Introduction

In the enterprise application development world, the buzzwords are

Performance, Scalability, and Security. I started my career as a VC++

programmer, and one fine morning, I was transferred to Web development

department. Like every C++ programmer, I also was frustrated. I thought

every Tom, Dick, and our very own Harry can program in HTML. But, soon

I found that the real challenge is to produce high performance,

scalable, and reliable applications. And above all that the loosely

coupled, stateless nature of web environment is always going to haunt

you.

In order to produce high performance scalable applications, it is

important to use your resources in an optimized manner. One tip is that

use your resource as late as you can and free it at the earliest after

your use. My intention here is to describe the object cleaning up

mechanism used in C#.

Destructors

As we all know, ‘Destructors’ are used to destruct instances of

classes. When we are using destructors in C#, we have to keep in mind

the following things:

A class can only have one destructor.

Destructors cannot be inherited or overloaded.

Destructors cannot be called. They are invoked automatically.

A destructor does not take modifiers or have parameters.

The following is a declaration of a destructor for the class MyClass:

~ MyClass()

{

// Cleaning up code goes here

}

The programmer has no control on when the destructor is going to be

executed because this is determined by the Garbage Collector. The

garbage collector checks for objects that are no longer being used by

the application. It considers these objects eligible for destruction

and reclaims their memory. Destructors are also called when the program

exits. When a destructor executes what is happening behind the scenes

is that the destructor implicitly calls the Object.Finalize method on the object's base class. Therefore, the preceding destructor code is implicitly translated to:

protected override void Finalize()

{

try

{

// Cleaning up .

}

finally

{

base.Finalize();

}

}

Now, let us look at an example of how destructors are called. We have three classes A, B and C. B is derived from A, and C is derived from B. Each class has their own constructors and destructors. In the main of the class App, we create an object of C.

using System;

class A

{

public A()

{

Console.WriteLine("Creating A");

}

~A()

{

Console.WriteLine("Destroying A");

}

}

class B:A

{

public B()

{

Console.WriteLine("Creating B");

}

~B()

{

Console.WriteLine("Destroying B");

}

}

class C:B

{

public C()

{

Console.WriteLine("Creating C");

}

~C()

{

Console.WriteLine("Destroying C");

}

}

class App

{

public static void Main()

{

C c=new C();

Console.WriteLine("Object Created ");

Console.WriteLine("Press enter to Destroy it");

Console.ReadLine();

c=null;

//GC.Collect();

Console.Read();

}

}

As we expect, the constructors of base classes will be executed and

program will wait for the user to press 'enter'. When this occurs, we

set the object of class C to null.

But the destructors are not executing ..!!?? As we already said, the

programmer has no control on when the destructor is going to be

executed because the Garbage Collector determines this. But the

destructors are called when the program exits. You can check this by

redirecting the o/p of the program to a text file. I have the output

here. Notice that the destructors of the base classes are called

because behind the scenes base.Finalize() is called.

Creating A

Creating B

Creating C

Object Created

Press enter to Destroy it

Destroying C

Destroying B

Destroying A

So, what do you do if you want to call the destructors once you are finished using the object? There are two ways:

Call the Garbage collector to clean up.

Implement Dispose method of IDisposable interface.

Calling the garbage collector

You can force the garbage collector to do clean up by calling the GC.Collect

method, but in most cases, this should be avoided because it may result

in performance issues. In the above program, remove the comment on GC.Collect(). Compile and run it. Now, you can see the destructors being executed in the console itself.

Implement IDisposable interface.

The IDisposable interface contains only one public method with signature void Dispose().

We can implement this method to close or release unmanaged resources

such as files, streams, and handles held by an instance of the class

that implements this interface. This method is used for all tasks

associated with freeing resources held by an object. When implementing

this method, objects must seek to ensure that all held resources are

freed by propagating the call through the containment hierarchy.

class MyClass:IDisposable

{

public void Dispose()

{

//implementation

}

}

When we implement IDisposable interface, we require discipline to ensure that Dispose is called properly.

Using the Destructor and IDisposable interface togetherPublic class MyClass:IDisposable

{

private bool IsDisposed=false;

public void Dispose()

{

Dispose(true);

GC.SupressFinalize(this);

}

protected void Dispose(bool Diposing)

{

if(!IsDisposed)

{

if(Disposing)

{

//Clean Up managed resources

}

//Clean up unmanaged resources

}

IsDisposed=true;

}

~MyClass()

{

Dispose(false);

}

}

Here the overload of Dispose(bool)

does the cleaning up, and all the cleaning up code is written only in

this method. This method is called by both the destructor and the IDisposable.Dispose(). We should take care that the Dispose(bool) is not called from any where else except from the IDisposable.Dispose() and the destructor.

When a client calls IDisposable.Dispose(), then the

client deliberately wants to clean up the managed and unmanaged

resource, and so the cleaning up is done. One thing you must have

noticed is that we called GC.SupressFinalize(this)

immediately after we cleaned up the resource. This method tells the

Garbage Collector that there is no need to call its destructor because

we have already done the clean up.

Notice that in the above example, the destructor calls the Dispose with parameter as false.

Here, we are ensuring that the Garbage collector collects the managed

resources. We only do the cleaning up of unmanaged resource.

Conclusion

Even though we have spent some time implementing the IDisposable interface, what if the client doesn’t call them properly? C# has a cool solution for this. The ‘using’ block. It looks like this:

using (MyClass objCls =new MyClass())

{

}

When the control exits from the using block either by running successfully and reaching the closing braces or by throwing an exception, the IDispose.Dispose() of MyClass will be executed. Remember the object you instantiate must implement the System.IDisposable interface. The using statement defines a scope at the end of which an object will be disposed.

About Ansil

Ansil

is an MCAD in .NET and he hails from Trivandrum .He is an independent

consultant and has got software development experiences in ASP.NET ,MFC

,Visual C# ,ASP , Sql Server2000 ,C# WebServices , COM+ and XML .He

spends his time reading technical articles ,searching the net for

latest news about various technologies,and he plays cricket and has a

passion of watching horror movies .

"First they ignore you;then they laugh at you ;then they fight you ;then you win "Click here to view Ansil's online profile.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
>>返回首页<<
推荐阅读
 
 
频道精选
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
© 2005- 王朝网络 版权所有