调用Dispose()当一个对象超出范围/法VS结束 [英] Calling Dispose() vs when an object goes out scope/method finishes

查看:201
本文介绍了调用Dispose()当一个对象超出范围/法VS结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它内部有一个try / catch / finall块。在try块,我宣布SqlDataReader对象如下:

I have a method, which has a try/catch/finall block inside. Within the try block, I declare SqlDataReader as follows:

                SqlDataReader aReader = null;          
               aReader = aCommand.ExecuteReader();

在finally块,这是手工处理的对象是那些被设置在类的级别。因此,在其中实现IDisposable方法的对象,如上面SqlDataReader的,他们得到自动处理的?关闭()调用aReader后while循环执行以得到读者的内容(这应该是Dispose()方法作为调用Close())。如果没有调用close(),将这个对象被关闭/处置时自动方式完成或对象超出范围

In the finally block, the objects which are manually disposed of are those which are set at the class level. So objects in the method which implement IDisposable, such as SqlDataReader above, do they get automatically disposed of? Close() is called on aReader after a while loop executes to get the contents of the reader (which should be Dispose() as that calls Close()). If there is no call to Close(), would this object be closed/disposed of automatically when the method finishes or the object goes out of scope?

编辑:?我注意使用()语句,但也有这些困惑我的情景。谢谢

I am aware of the using() statement but there are scenarios which are confusing me. Thanks

感谢

推荐答案

没有,对象不会自动处置时他们走出去的范围。

No, objects are not automatically disposed when they go out of scope.

他们甚至不保证进行处理,如果/当他们是垃圾收集,虽然许多 IDisposable的对象实现了回退finaliser以确保他们最终处置。

They're not even guaranteed to be disposed if/when they're garbage-collected, although many IDisposable objects implement a "fallback" finaliser to help ensure that they're eventually disposed.

您是resposible确保任何 IDisposable的物品设置,最好是通过在 使用 块。

You are resposible for ensuring that any IDisposable objects are disposed, preferably by wrapping them in a using block.

这篇关于调用Dispose()当一个对象超出范围/法VS结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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