在表达式中创建的图像是否会立即处理?
这足够了吗:
using (Graphics g = Graphics.FromImage(image))
{
g.DrawImage(newImage.GetThumbnailImage(10, 10, null, new IntPtr()), 3, 3, 10, 10);
}
或者我应该使用:
using (Graphics g = Graphics.FromImage(image))
{
using (Image i = newImage.GetThumbnailImage(10, 10, null, new IntPtr()))
{
g.DrawImage(i, 3, 3, 10, 10);
}
}
编辑: 有人可以添加一些 MS 引用,即使没有创建变量,资源也不会立即释放吗?
Is this enough:
using (Graphics g = Graphics.FromImage(image))
{
g.DrawImage(newImage.GetThumbnailImage(10, 10, null, new IntPtr()), 3, 3, 10, 10);
}
Or should I use:
using (Graphics g = Graphics.FromImage(image))
{
using (Image i = newImage.GetThumbnailImage(10, 10, null, new IntPtr()))
{
g.DrawImage(i, 3, 3, 10, 10);
}
}
EDIT:
Can someone please add some MS reference that even when there is no variable created – the resources will not be freed immediately?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非您专门调用它的
Dispose()
方法(或者它留下一个using
块),否则它不会被释放。因此,在您的情况下,使用第二个using
块将是确保释放非托管资源的更安全的选择。It's not going to be disposed unless you specifically call the
Dispose()
method on it (or it leaves ausing
block). So in your case, using the secondusing
block would be the safer choice to make sure you free unmanaged resources.对于实现
IDisposable
的类型,您应该使用using
语句。否则,在对象完成之前不会释放资源。为了使代码更整洁,我喜欢堆叠
using
块You should use a
using
statement for types that implementIDisposable
. Otherwise, the resources won't be freed until the object is finalized.To make the code a tad neater, I like to stack
using
blocks垃圾收集器不仅不会立即触发,而且如果对象持有系统资源(例如文件),它可能无法正确清除对象。虽然我不确定 Image 类,但是,如果您的代码必须(有一天)在内存紧张的情况下运行,您希望在完成图像后立即清理图像。这就是
using
和IDisposable
发挥作用的地方。我曾经发现过一个关于使用块的非常好的博客 此处,以下代码:
将表现得与此完全相同:
因此,即使您的代码抛出异常,它也会清理您的图像,并且如果你叫自己处置。
简而言之:始终将 using 与实现 IDisposable 的对象一起使用,此外,如果代码很复杂,请在不再需要该对象时自行调用 Dispose - 并将对象引用设置为 null。
Not only will garbage collector not trigger immediatelly, but it might not clear the objects correctly if they hold system resources - like files. I am not sure about Image class though, but still, should your code have to (some day) run on a tight memory, you want image cleaned immediatelly when you are done with it. This is where
using
andIDisposable
come in.I found a very good blog once about Using block here, following code:
will behave exactly like this:
So it will clean your Image even if your code throws and exception, and it will cause no problem if you call dispose yourself.
In short: always use using with objects that implement IDisposable, in addition, if the code is complex, call Dispose yourself as soon as you do not need the object anymore - and set the object reference to null.