Ava*_*his 5 .net c# user-controls .net-4.0 winforms
我一直在追踪内存泄漏,我把它缩小到一个在UserControl派生类中分配的ToolTip.
ToolTip在控件的构造函数中分配,并在Load事件中初始化,如下所示:
public class CommonProfile : System.Windows.Forms.UserControl
{
private ToolTip toolTip1;
...
public CommonProfile()
{
InitializeComponent();
// Create the ToolTip and associate with the Form container.
toolTip1 = new ToolTip(this.components);
}
private void CommonProfile_Load(object sender, System.EventArgs e)
{
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;
// Set up the ToolTip text
toolTip1.SetToolTip(this.btnDeleteEntry, "Delete this Profile");
toolTip1.SetToolTip(this.lblProfileType, "Edit this Profile");
toolTip1.SetToolTip(this.lblProfileData, "Edit this Profile");
toolTip1.SetToolTip(this.picFlagForUpdate, "Toggle Flag for Update");
}
}
Run Code Online (Sandbox Code Playgroud)
控件的父级的生命周期超过了控件的生命周期.此控件即时创建并添加到面板控件,然后从面板控件中删除.
我发现控件的Dispose成员没有被调用,显然是因为对ToolTip的引用仍然存在.
我添加了一个这样的Shutdown方法:
public void Shutdown()
{
toolTip1.RemoveAll();
}
Run Code Online (Sandbox Code Playgroud)
调用Shutdown方法可以消除泄漏,并最终调用Dispose.
不幸的是,这个解决方案要求使用控件的人记住在完成它时调用Shutdown方法.
我想知道是否有某种方法可以自动执行此操作,以便在不需要显式调用Shutdown方法的情况下实现.
您没有显示如何UserControl从Panel.
只需调用:
panel1.Controls.Remove(userControl1);
Run Code Online (Sandbox Code Playgroud)
不会处置UserControl.
您需要专门致电:
userControl1.Dispose();
Run Code Online (Sandbox Code Playgroud)
这也会自动将其从Panel. 在您的 中UserControl,如果您需要自己进行清理,请尝试订阅它自己的 Dispose 事件:
private ToolTip toolTip1;
public UserControl1() {
InitializeComponent();
// tooltip initialization
this.Disposed += UserControl1_Disposed;
}
private void UserControl1_Disposed(object sender, EventArgs e) {
if (toolTip1 != null)
toolTip1.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4266 次 |
| 最近记录: |