在c#中定义对象时使用
当我们使用using来定义一个对象时?例如:
using (Login objLogin = new Login())
我知道我们在使用这个对象后想要清理内存时使用,但我不知道我们什么时候应该清理内存。
when we use using for defining an object?for example:
using (Login objLogin = new Login())
i know that we use when we want to clean the memory after using this object but i dont know when should we clean the memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应使用
using
语句及时处置实现IDisposable
的对象。这实际上并不清理托管内存,而是允许托管对象释放它可能持有的任何非托管资源,并在某些情况下删除对托管对象的引用以防止内存泄漏。我建议阅读以下网站,这些网站提供了
IDisposable
和using
语句的深入解释The
using
statement should be used to timely dispose of objects which implementIDisposable
. This does not actually clean managed memory but allows a managed object to release any unmanaged resources it may be holding and in some occasions remove references to managed objects to prevent memory leaks.I suggest reading up on the following sites which provide in depth explanations of both
IDisposable
and theusing
statement每当一个对象是一次性的(它实现了 IDisposable 接口)时,这意味着它可能使用一些无法由垃圾收集器管理的非托管资源,因此,如果您的对象被收集,这些资源可能会保留在内存中,从而导致一些问题。这个问题的解决方案是:
1.在此类对象中实现 IDisposable 接口,并在 Dispose 方法中清除/关闭非托管资源(例如,如果您在对象内部使用一次性对象,最好有一个 Dispose方法内部调用其 dispose)
2.当不再需要一次性对象时,调用一次性对象的 Dispose 方法,但要小心,因为重用已处置的对象可能会引发一些异常。
您提到的 using 语法是执行相同操作的一种简短方法,它将 this: 解释
为以下内容:
因此您始终可以确保无论发生什么,对象的 Dispose 方法总是被调用。
Whenever an object is disposable (it implements IDisposable interface) it means that it probably uses some unmanaged resources that can not be managed by garbage collector and therefore if your object is collected these resources might remain in the memory causing some problems. The solution for this problem is :
1.To implement IDisposable interface in such kind of objects and to clear/close unmanaged resources in Dispose method (for example if you are using a disposable object inside your object it'd be better to have a Dispose method to call its dispose inside)
2.To call the Dispose method of disposable objects when they are not needed anymore but be careful cause reusing a disposed object can throw some exceptions.
The using syntax that you mentioned is a short way of doing the same and it interprets this:
into following :
thus you can always be sure that whatever happens the Dispose method of your object is always called.
你不清理记忆;实现 IDisposable 的对象将在其 Dispose 方法中清理其非托管资源(或者至少,这是该类通过实现 IDisposable 所做的暗示),并且 .NET 将在收集对象时清理内存。
You don't clean the memory; the object implementing IDisposable will clean its unmanaged resources in its Dispose method (or at least, that's the implication that the class is making by implementing IDisposable), and .NET will clean the memory when the object is collected.