wpf userControl's子控件'取消订阅事件

本文关键字:事件 取消 userControl wpf 控件 | 更新日期: 2023-09-27 18:12:10

我希望有一个通用的(扩展)方法,它采取父控件和遍历到它的所有子控件和取消订阅他们的事件,如果有的话。

当我创建一些基于wpf的表单时,我正在密切关注内存消耗,考虑到ui元素及其事件的数量,内存峰值是预期的,但是当表单关闭时,我希望内存得到释放,就像wpf一样,我假设表单一旦关闭就会自动处理,因此GC应该清理并释放内存……但我等了几分钟,在诊断工具中查看了私有内存的使用情况,结果并没有改变。所以我想知道它没有完全处理/取消订阅事件等

wpf userControl's子控件'取消订阅事件

我不能说有很多订阅事件是否会对性能产生负面影响,但我可以肯定地回答您的其他两个问题:

  1. 您可以使用以下扩展名枚举所有子节点:

    public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject Parent) where T : DependencyObject
    {
        if (Parent != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(Parent); i++)
            {
                var Child = VisualTreeHelper.GetChild(Parent, i);
                if (Child != null && Child is T)
                    yield return (T)Child;
                foreach (var ChildOfChild in GetVisualChildren<T>(Child))
                    yield return ChildOfChild;
            }
        }
    }
    foreach (myControlInstance.GetVisualChildren<DependencyObject>())
    {
        //Unsubscribe events
    }
    
  2. 要取消订阅对象中的所有事件,请参阅SO文章:

如何在c#中取消订阅特定类的事件的所有处理程序?