Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Is there an Advantage to Disposing Resources in Reverse Order of their Allocation?

Many years ago, I was admonished to, whenever possible, release resources in reverse order to how they were allocated. That is:

block1 = malloc( ... );
block2 = malloc( ... );

... do stuff ...

free( block2 );
free( block1 );

I imagine on a 640K MS-DOS machine, this could minimize heap fragmentation. Is there any practical advantage to doing this in a C# /.NET application, or is this a habit that has outlived its relevance?

like image 402
Bob Kaufman Avatar asked Nov 09 '09 19:11

Bob Kaufman


1 Answers

If your resources are created well, this shouldn't matter (much).

However, many poorly created libraries don't do proper checking. Disposing of resources in reverse of their allocation typically means that you're disposing of resource dependent on other resources first - which can prevent poorly written libraries from causing problems. (You never dispose of a resource, then use one that's depending on the first's existence in this case.)

It also is good practice, since you're not going to accidentally dispose a resource required by some other object too early.

Here's an example: look at a database operation. You don't want to close/dispose your connection before closing/disposing your command (which uses the connection).

like image 170
Reed Copsey Avatar answered Oct 04 '22 09:10

Reed Copsey