欢迎光临
我们一直在努力

Destructors in C#-.NET教程,C#语言

建站超值云服务器,限时71元/月

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 objects 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 together

public 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 ansils online profile.

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Destructors in C#-.NET教程,C#语言
分享到: 更多 (0)