自定义控制和处理 [英] Custom control and dispose
问题描述
故事的开始是此处。
我有一个组件,希望它清理计时器(托管资源,对吗?):
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();
}
}
如您所见,我试图再实现一个(oO) IdDisposable
(尽管PictureBox-> Control-> Component-> IDisposable)。
As you can see, I tried to implement one more (oO) IdDisposable
(despite PictureBox->Control->Component->IDisposable). But.. none of them is called.
控件是通过使用设计器放置在窗体上的。但是它没有出现在 Components
表单中,这应该是处理表单时不调用它的原因:
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
我的问题是我应该如何组织处置控件计时器满足我的需要-处置MyPictureBox计时器以及处置形式?
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?
推荐答案
您将必须覆盖 Dispose(布尔处置)
。无需显式实现 IDisposable
。
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);
}
这篇关于自定义控制和处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!