如何GC和IDispose在C#中的工作? [英] How does GC and IDispose work in C#?

查看:136
本文介绍了如何GC和IDispose在C#中的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得我被它的净流直入位图加载图像中。关闭流,返回的位图和图像控件中举行了。

I remember i was loading in images by streaming it from the net straight into a bitmap. close the stream, return the bitmap and held it in an image control.

我例外,当我做=的LoadPicture()第一个位图将释放像一个智能指针会做在C ++中。但它没有,我消耗了大量的RAM,直到我打电话处置。所以我的问题是。

I excepted when i did = loadPicture() the first bitmap would be freed like a smart pointer would do in C++. But it didnt and i consumed a lot of ram until i called dispose. So my question is.

如何GC和处置能力的对象在C#中的工作?为什么不是它实现像smart_ptr?

How does the GC and Dispose able objects work in C#? and why isnt it implemented like a smart_ptr?

推荐答案

引用不聪明指针。让一个参考变量走出去的范围,与另一个值替换它,和/或与空做的都是将其设置的什么

References are not smart pointers. Letting a reference-variable go out of scope, replacing it with another value, and/or setting it with null all do exactly nothing.

这是简单的CLI / GC设计的一部分...

This is simply part of the CLI /GC design...

Gargage回收(GC)运行的在需要的时候的,应该清理所使用的管理的内存,并且(如果提供了终结器)的任何非托管资源太多。但对于确定性的清理:那就是的IDisposable 的全部目的。这是你的工作,的Dispose()这样的对象,当你完成了他们 - 或者通过使用,或移交它别的东西而承担这一责任(常见,例如,与流/读取器等)。

Gargage Collection (GC) will run when needed, and should clean up the managed memory used, and (if a finalizer is provided) any unmanaged resources too. But for deterministic cleanup: that is the entire purpose of IDisposable. It is your job to Dispose() such objects when you have finished with them - either via using, or by handing it to something else which assumes this responsibility (common, for example, with streams/readers etc).

using (StreamReader reader = new StreamReader(myfile)))
{
   ...
}

这篇关于如何GC和IDispose在C#中的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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