Event Handler Stops Working After Dispose

江枫思渺然 提交于 2019-12-13 05:24:25

问题


The three ImageButtons below are added to a panel (pBreakfast) in a page's codebehind:

ImageButton ibSR = new ImageButton();
ibSR.ID = "ibStickyRoll";
ibSR.ImageUrl = "/images/Breakfast.gif";
ibSR.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibSR);

ImageButton ibD = new ImageButton();
ibD.ID = "ibDoughnut";
ibD.ImageUrl = "/images/Breakfast.gif";
ibD.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibD);
ibD.Dispose();

using(ImageButton ibC = new ImageButton()){
   ibC.ID = "ibCrepe";
   ibC.ImageUrl = "/images/Breakfast.gif";
   ibC.Click += new ImageClickEventHandler(ImageButton_Click);
   pBreakfast.Controls.Add(ibC);
}

I expected either all three would work, or perhaps the disposed ImageButtons would generate an error or simply not appear. But what's happening is all three appear and don't cause any errors, but the event handler never fires for the ImageButtons that are disposed.

Why does disposing cause only the eventhandler hookup to go away?

I am dynamically adding TableRow's and TableCell's to a table on this same page and placing ImageButtons in one cell of each row. I am using 'using' with the TableRow's and TableCell's without any problem. There doesn't seem to be an issue with the outer (TableRow & TableCell) objects getting disposed; as long as I don't ever dispose of the dynamic ImageButtons, the eventhandler gets fired OK on click.

Is it OK, in this instance, to not ever dispose of the ImageButtons? I have taken StackOverflow's advice to heart and try to use using() on all my disposable objects -- so this is really bugging me.

Thanks!


回答1:


Only Dispose an object after everything is completely done with it. Trying to do anything with the object after it is disposed will result in undefined behavior. Think of it as freeing the memory.

Fortunately, Windows forms disposes these objects for you when you close the form. The only case you would need to dispose them in your code is if you remove the objects from the form.

Take a look at the .Designer.cs file, and you will see the form's Dispose() method:

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

The components.Dispose() will recursively clean up all the components on the form, including those in the panel.



来源:https://stackoverflow.com/questions/21316266/event-handler-stops-working-after-dispose

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