C#:以相反的顺序分配资源是否有优势? [英] C#: Is there an Advantage to Disposing Resources in Reverse Order of their Allocation?

查看:96
本文介绍了C#:以相反的顺序分配资源是否有优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多年前,我被告诫,只要有可能,就以与分配资源相反的顺序释放资源.那就是:

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 );

我想象在640K MS-DOS机器上,这可以使堆碎片最小化.在C#/.NET应用程序中执行此操作是否有任何实际优势,还是这已经使它不再重要了?

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?

推荐答案

如果您的资源创建良好,那么这无关紧要.

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).

这篇关于C#:以相反的顺序分配资源是否有优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆