Search code examples
.netdisposevisualizer

Do i need to dispose of this Image instance?


I'm making a simple Image Debugger Visualizer. Code is below. I'm not sure if i need to manually dispose of the Image instance? Because i'm making a windows Form window and the PictureBox inside that contains my dynamic image .. do i need to add some special code when the form is terminating, to dispose of this?

here's the code..

using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.DebuggerVisualizers;
using DebuggerVisualizers;

[assembly: DebuggerVisualizer(
    typeof (ImageDebuggerVisualizer),
    typeof (VisualizerObjectSource),
    Target = typeof (Image),
    Description = "Image Visualizer")]

namespace DebuggerVisualizers
{
    public class ImageDebuggerVisualizer : DialogDebuggerVisualizer
    {
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            Image image = (Image) objectProvider.GetObject();
            Form form = new Form
                           {
                               Text = ("Image Visualizer - " + image.HorizontalResolution + " " + image.VerticalResolution),
                               Width = image.Width,
                               Height = image.Height
                           };

            PictureBox pictureBox = new PictureBox {Image = image, SizeMode = PictureBoxSizeMode.AutoSize};
            form.Controls.Add(pictureBox);
            form.ShowDialog();
        }
    }
}

thanks for any help :)


Solution

  • Change your Show method to this:

    protected override void Show(IDialogVisualizerService windowService,
        IVisualizerObjectProvider objectProvider)        
    {            
        Image image = (Image) objectProvider.GetObject();
        using (Form form = new Form())
        {            
            PictureBox pictureBox = new PictureBox();    
            pictureBox.Image = image;        
            form.Controls.Add(pictureBox); 
            form.ShowDialog();
        } 
    }
    

    The using(){} block will call Dispose on the form after it closes, which will dispose of everything on the form also.