Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - How can I completely delete PictureBox (+ release memory)

I'm trying to delete my PictureBox completely as I don't need it anymore. I tried to use Dispose() method and this removed the PBox from the Form correctly, but not from the memory... After I applied Dispose(), I created a PBox and load the same image in it, then called Dispose() again and so on... What I see in the 'Diagnostic Tools / Process memory' window is the memory usage increased each time when I press the button (which create new PBox and load image into it), but the memory is never released... I also tried to use Controls.Remove() method but I got the same result!

So the question is: How can I release the memory and remove a PictureBox completely?

EDIT: Ok.. after a while when the program used up about 1Gb of memory (by create PBox/Dispose cycle) the garbage collector activated itself and released almost all of the memory used by the program! I misunderstood how this works... I thought it should have ran each time after I use Dispose method.. so looks all good, but is there any way to release PBox from memory manually after I applied Dispose?

question from:https://stackoverflow.com/questions/65648239/how-can-i-completely-delete-picturebox-release-memory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally, you should call Dispose and drop all references to the PictureBox. Some time later the GC will collect this PictureBox and free the memory. But it is no way to know, when exactly GC will run. So, the memory usage may increase for some time before GC will run - it is normal. In most cases you should not manually force GC to run, but in some specific cases you can do this with GC.Collect(); (but it strongly not recommended)

Update You can't manually "collect/free" only specified object. Only force GC (and get all the possible problems, mentioned by the link above).

The better solution may be to rework your code to avoid recreation of ImageBoxes. You can try

  • show/hide the single ImageBox and just replacing the image inside it
  • cache the ImageBox object and add/remove it from the form with Controls.Add/Controls.Remove.

You will still get some memory traffic due to loading/disposing images, but it may be better then recreation of a whole ImageBox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...