Silverlight内存泄漏

时间:2011-09-10 12:22:14

标签: silverlight

好吧,我试过这个,内存分析器显示问题仍然没有解决, 实际上我删除了我正在使用以下代码创建一个使用回调方法更改的DependencyProperty:

public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback) 
{ 
    Binding b = new Binding(propertyName) { Source = element }; 
    var prop = System.Windows.DependencyProperty.RegisterAttached( 
        "ListenAttached" + propertyName, 
        typeof(object), 
        typeof(UserControl), 
        new System.Windows.PropertyMetadata(callback));              
    element.SetBinding(prop, b); 
}  

好吧,我试过这个,内存分析器显示问题仍然没有解决, 实际上我删除了element.SetBinding(prop,b);和内存泄漏仍然发生所以我thisnk它的原因不是绑定它自己,但这段代码:     var prop = System.Windows.DependencyProperty.RegisterAttached(             “ListenAttached”+ propertyName,             的typeof(对象),             typeof运算(用户控件),             新的System.Windows.PropertyMetadata(回调));
当我使用null而不是回调时,泄漏没有发生。这意味着原因是回调方法没有绑定,有没有办法取消注册呢?或以其他方式注册,以免造成泄漏?

非常感谢Phil Sandler,它真的很有帮助并且工作正常

我试图将visibilitychanged监听器添加到我的用户控件中,所以我将该方法称为 RegisterForNotification(“可见性”,这个,回调),导致内存泄漏,

我使用了你这样的吸气:

公共字符串ListenAttachedVisibility         {             get {return(string)GetValue(SelectedValueBindingProperty); }             set {SetValue(SelectedValueBindingProperty,value); }         }

    public static readonly DependencyProperty ListenAttachedVisibilityProperty =
 DependencyProperty.Register("ListenAttachedVisibility", typeof(object), typeof(UserControl),
 new System.Windows.PropertyMetadata(null, new PropertyChangedCallback(OnVisibilityChanged)));

    private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {


        // call to instance method 
        ((DualLOV)d).OnVisibilityChanged(e);
    }
    protected virtual void OnVisibilityChanged(DependencyPropertyChangedEventArgs e)
    {
        ClearValues(e.NewValue);
    }

然后我做了绑定:             绑定b =新绑定(“可见性”){Source = this};             this.SetBinding(ListenAttachedVisibilityProperty,b);

并且visibilty改变事件工作正常,内存泄漏也消失了。 再次感谢。

2 个答案:

答案 0 :(得分:1)

您的原始(预编辑)帖子似乎表明您有内存泄漏。我猜测问题是你创建了一个依赖属性作为实例变量。你永远不想这样做,导致内存泄漏。

编辑:

我不清楚你要做什么。但是你的Dependency Property应该在类级别声明,它应该是static readonly

删除回调修复泄漏是有道理的,因为回调是“短期订阅者”而DP是“长期存在的发布者”。 DP是长期存在的,因为框架不知道如何清理它,因为框架期望DP被声明为static readonly(我无法解释为什么,这就是它在Silverlight中的工作方式)

看起来您正在尝试使用动态绑定或通知执行某些操作。无论你想要做什么或不做什么都是另一个问题的主题,但无论解决方案如何,必须基于正确使用(和声明)的依赖属性。

答案 1 :(得分:0)

BindingOperations.ClearBinding()方法在内部调用ClearValue()。我们知道通过在Reflector中查找它。

public static void ClearBinding(DependencyObject target, DependencyProperty dp)
{
    if (target == null)
    {
        throw new ArgumentNullException("target");
    }
    if (dp == null)
    {
        throw new ArgumentNullException("dp");
    }
    if (IsDataBound(target, dp))
    {
        target.ClearValue(dp);
    }
}

您可以在班上使用相同的方法。

P.S。答案来自this问题。