Custom control and dispose

假如想象 提交于 2020-01-24 23:54:50

问题


The start of story is here.

I have a component and I want it to clean up timers (managed resources, right?):

public class MyPictureBox : PictureBox, IDisposable
{
    private Timer _timer1 = new Timer();
    private Timer _timer2 = new Timer();
    public MyPictureBox(): base()
    {
        _timer1.Interval = 100;
        _timer1.Start();
        _timer2.Interval = 250;
        _timer2.Start();
    }

    // ... all sort of code


    new void Dispose()
    {
        base.Dispose();
        _timer1.Dispose();
        _timer2.Dispose();
    }

    void IDisposable.Dispose()
    {
        _timer1.Dispose();
        _timer2.Dispose();
    }
}

As you can see, I tried to implement one more (oO) IdDisposable (despite PictureBox->Control->Component->IDisposable). But.. none of them is called.

Control is put on form by using designer. But it is doesn't appears in form Components and this should be the reason why it is not called when form is disposed:

Form1 form = new Form1();
form.Dispose(); // MyPictureBox.Dispose() are not called

My question is how should I organize disposing of my control timers to have what I needed - disposing of MyPictureBox timers together with form disposing?


回答1:


You'll have to override Dispose(bool disposing). and no need to explicitly implement IDisposable.

protected override void Dispose(bool disposing)
{
    _timer1.Dispose();
    _timer2.Dispose();
    base.Dispose(disposing);
}



回答2:


Although Sriram's answer is correct, if you are using unmanaged types, such as COM objects, you should use the Finalizer pattern:

public class MyPictureBox : PictureBox, IDisposable
{
    private Timer _timer1 = new Timer();
    private Timer _timer2 = new Timer()

    //more of your stuff 

    ~MyPictureBox ()
    {
        Dispose(false);
    }

    protected override void Dispose(bool disposing)
    {
         //clean up unmanaged here

        if(disposing)
        {
            _timer1.Dispose();
            _timer2.Dispose();
        }

        base.Dispose(disposing);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

See Dispose Pattern: http://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx

As you are using a PictureBox, keep in mind that must Image types are IDisposable as well.



来源:https://stackoverflow.com/questions/20073750/custom-control-and-dispose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!