如果要替换PictureBox控件中的图像,是否应该首先处理原始图像? [英] If I replace an image in a PictureBox control, should I dispose the original image first?

查看:128
本文介绍了如果要替换PictureBox控件中的图像,是否应该首先处理原始图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接着是我的问题在这里,如果我将图片替换在图片框中,应该先丢弃原始图片吗?

Following on from my question here, if I replace an image in a picture box, should I dispose the original image first?

或者,这种情况如何?

Dim bm As New Bitmap(32,32)  
bm = New Bitmap(32,32)  
bm = New Bitmap(32,32)  
bm = New Bitmap(32,32)  

bm是否只需要放置在最后,还是应该在每次重新创建之前放置?

Does bm need only to be disposed at the end, or should it be disposed before each re-creation?

谢谢大家的回答.在我这方面,这是一个很大的疏忽.我知道控件会处理掉它的子项,但是我没有想到如果替换掉旧的图像,我应该废弃它.

Thanks all for the answers. A big oversight there on my part. I knew a control took care of disposing its children but It hadn't occurred to me that I should dispose an old image if I replaced it.

推荐答案

是的,在相同变量之上创建新图像之前,应先处置旧对象.通过使用相同的变量创建新图像,您将删除对该图像的引用.如果没有对旧对象的引用,则表示应由GC(垃圾收集器)对其进行拾取.尽管从技术上讲,这种应该"最终会导致内存被释放,但前提是该终结器确保已处理非托管资源,但这是一个很大的假设(您甚至无法真正假设将调用终结器) ,这会为系统带来更多工作.非默认终结器在垃圾回收级别提升方面为GC带来了额外的工作,从而导致需要更长的时间来释放内存,并需要花费一定的次数来运行GC.

Yes, you should dispose the old object before you create a new image on top of the same variable. By creating a new image with the same variable, you are removing a reference to it. If there are no references to the old object, you are signifying that it should be picked up by the GC (Garbage Collector). Although technically, this "should" eventually result in the memory being freed assuming that the finalizer makes sure that non-managed resources are taken care of, this is a big assumption (You can't even really assume that the finalizer will be called), and it causes more work for the system. Non-default finalizers causes extra work for the GC in terms of garbage collection level promotion, resulting in taking longer for the memory to be deallocated, and the number of times the GC has to run to do so.

这是为了确保终结器能够处理而编写的.只要对象具有Dispose方法(任何实现BitMap的实现IDisposable的方法),都应在删除对对象的引用(超出范围,删除对对象的引用等)之前调用它.

This is assuming that is all written to make sure the finalizer handles it. Anytime an object has a Dispose method (anything which implements IDisposable which BitMap does), it should be called before removing reference to the object (falling out of scope, removing reference to the object etc.).

此处是有关.net中垃圾收集器如何工作的文章

Here is an article on how the Garbage Collector works in .net

http://www.devx.com/dotnet/Article/33167

这是MS所说的处置/终结器应该实现的方式:

Here is how MS says the dispose / finalizer should be implemented:

http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

这篇关于如果要替换PictureBox控件中的图像,是否应该首先处理原始图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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