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?
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);
}