开发者

Delete / Kill / Remove UserControl and its events handlers

开发者 https://www.devze.com 2023-01-15 12:13 出处:网络
I dynamically create UserControls using Reflection: UserControl myConmtrol = (UserControl)Activator.CreateInstance(t);

I dynamically create UserControls using Reflection: UserControl myConmtrol = (UserControl)Activator.CreateInstance(t);

The UserControl may handle a Closing event but I do not know the name of the handler.

When the Window hosting the UserControl closes I remove the UserControl from its parent Window and it disappears from the Window: Everything seems OK.

But if I open and cl开发者_如何学Pythonose again the UserControl I can see in the debugger the Closing event is handled twice, one time by the current UserControl but also by the previous UserControl that is still alive.

Theorically the UserControl being no longer referenced should be GarbageCollected. How can I force it to be Killed/Deleted/Disposed ? At least is there a way to forbid it handles events ?

Thanks


Not sure without more detail but i would start and check if you have any event handlers that isn't removed

Do I need to remove event subscriptions from objects before they are orphaned?


Answer about removing handlers without knowing their names:

public void RemoveHandlerOfUserControl(UserControl uc)
{

    MulticastDelegate dlg = MyEvent;
    Delegate[] handlers = dlg.GetInvocationList();
    foreach (Delegate d in handlers)
    {
        if (d.Target == uc)
        {
            this.RemoveHandler(MyEvent, d);
        }
    }
 }

This method must reside in the object where the event is declared.


I had to cope with the same situation in Winforms where I dynamically create a user control inside another user control (Let's say a "DynControl" inside "HostControl").

There is no Closing event in "HostControl". So I used the Disposed event of HostControl to release resources :

this.Disposed += (s, e1) => 
{
  DynControl.Click -= += new EventHandler(MyClickHandler);
  this.Controls.Remove(DynControl);
  DynControl.Dispose();
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号