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

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

问题描述

一旦你完成了它们,你是否应该将所有对象设置为 null(在 VB.NET 中为 Nothing)?

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

我知道在 .NET 中,必须处理任何实现了 IDisposable 接口的对象实例以释放一些资源,尽管对象在处理后仍然可以是某些东西(因此 IDisposablecode>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).

考虑到这一点,将其设置为 null 会加快系统释放内存的速度,因为它不必确定它不再在范围内,它们是否有任何不良副作用?

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.

推荐答案

Karl 是完全正确的,使用后不需要设置对象为空.如果对象实现了 IDisposable,请确保在完成该对象后调用 IDisposable.Dispose()(包装在 try 中)..finally,或者,一个 using() 块).但即使您不记得调用 Dispose(),对象上的终结器方法也应该为您调用 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

尝试重新猜测 GC 及其管理策略没有任何意义,因为它是自调整的且不透明.在 Dot Net Rocks 上与 Jeffrey Richter 就内部工作进行了很好的讨论:Jeffrey Richter onWindows 内存模型和Richters 的书 CLR via C# 第 20 章有很好的处理:

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/Nothing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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