在.NET中使用后,设置对象为Null /没有 [英] Setting Objects to Null/Nothing after use in .NET

查看:310
本文介绍了在.NET中使用后,设置对象为Null /没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你将所有的对象没有在VB.NET),一旦你已经完成了他们?

Should you set all the objects to null (Nothing in VB.NET) once you have finished with them?

据我所知,在.NET中,必须处理实现了的IDisposable 接口释放一些资源的对象的任何实例,虽然这个对象还可以后的东西配置(因此 isDisposed 属性的形式),所以我假定它仍可以驻留在内存中,或至少部分?

I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part?

我也知道,当一个对象超出范围时它然后标记为集合准备好了垃圾收集器的下传(尽管这可能需要一段时间)。

I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).

所以,考虑到这一点将其设置为加快系统释放内存,因为它没有制定出它不再是范围,因此他们任何不好的副作用?

So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?

MSDN文章从来没有做到这一点的例子,现在我做到这一点,因为我不能 见害。不过,我所遇到的意见的混合物所以任何意见是有用的。

MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.

推荐答案

卡尔是绝对正确的,也没有必要使用后,设置对象为null。如果一个对象实现的IDisposable ,只要确保你叫 IDisposable.Dispose()当你与该对象就大功告成了(包在尝试 .. 最后,或者,一个使用()块)。但是,即使你不记得叫做的Dispose(),在对象上finaliser方法应该调用的Dispose()给你。

Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try..finally, or, a using() block). But even if you don't remember to call Dispose(), the finaliser method on the object should be calling Dispose() for you.

我认为这是一个良好的治疗效果:

I thought this was a good treatment:

挖掘到了IDisposable

<一个href="http://web.archive.org/web/20090426210049/www.marcclifton.com/tabid/79/Default.aspx">Understanding IDisposable的

没有试图第二猜测GC和它的管理策略,因为它是自调整和不透明的任何一点。有关于与杰弗里里希特内部运作上点网岩在这里商量好了:杰弗里里希特Windows内存模式<上/ A>和 通过C#第20章有一个伟大的处理Richters书 CLR:

There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model and Richters book CLR via C# chapter 20 has a great treatment:

这篇关于在.NET中使用后,设置对象为Null /没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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