您的位置:首页 > 其它

wpf内存泄漏问题

2016-07-14 14:54 417 查看


wpf内存泄漏问题_同事小邱写的

1、   如果用MVVM模式,View里面有图片,ViewModel里面有View引用,要把ViewModel里面的View设置为空,View里面的DataContext设置为空,不然有可能导致内存泄漏
清除引用:
this.Page.DataContext = null;
this.Page = null;

2、   类与类之间尽量不要互相引用,如果相互引用了要手动设置里面的引用为空,不然 会导致内存泄漏
Class1 class1 =new Class1();
Class2 class2 = new Class2();
class1.Class2 = class2;
class2.Class1 = class1;
清除引用:
class2.Class1 = null;
class2 = null;
class1.Class2 = null;
class1 =null;

3、   自定义控件里面有Image、BitMapSource属性值之类或者引用类属性时,要手动删除并设置为空
CustomControl cc = new CustomControl();
BitMapSource bms = new BitMapSource();
bms.UriSource = ……;
cc.Image = new Image(){Source= bms };
清除引用:
cc.Image=null;
bms =null;

4、   MVVM模式里面继承INotifyPropertyChanged的ViewModel里面的命令(用CommandManager.RegisterClassCommandBinding)有可能导致内存泄漏
protected ICommand CreateCommand(Action<ExecutedRoutedEventArgs>
executed, Action<CanExecuteRoutedEventArgs> canExecute)
              {
            var rCommand = new RoutedCommand();
            var cBinding = new CommandBinding(rCommand);
            CommandManager.RegisterClassCommandBinding(typeof(UIElement),
cBinding);
            cBinding.CanExecute += (s, e) =>
            {
                if (canExecute != null)
                    canExecute(e);
                else
                    e.CanExecute = true;
            };
            cBinding.Executed += (s, e) =>
            {
                executed(e);
            };
 
                     return rCommand;
               }
修改成:

protected ICommand CreateCommand(Action<object>
execute)
        {
            return new RelayCommand(execute);
        }

public class RelayCommand : Icommand

{

        ………….

}
 

5、   页面关闭时没结束的线程要结束线程

6、   页面关闭时静态变量要设置为空

7、   使用事件时,如果是一个类的事件在另一个类里面被注册(委托方法在这个类里面),要注销事件
Window1.w2.TextBox1.TextChanged += new TextChangedEventHandler(this.TextBox1_TextChanged);
Window1.w2.TextBox1.TextChanged -= new TextChangedEventHandler(this.TextBox1_TextChanged); 事件

8、                   用静态事件时要注销事件

9、                   在Image里面使用BitMapImage时要用


BitmapImage bi = new BitmapImage();

bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.UriSource = new Uri(path);
                bi.EndInit();
                bi.Freeze();

10、        调用垃圾回收
GC.Collect();

   GC.WaitForPendingFinalizers();

   GC.Collect();

11、               如果绑定的数据源没有实现INotifyPropertyChanged,可能导致内存泄漏

在 WPF 中,不标记为 OneTime 必须侦听属性的一个数据绑定操作从源对象 (对象 X) 更改通知。WPF 从 INotifyPropertyChanged 界面使用 DependencyProperties 类的内置通知。

如果 DependencyProperties 类和 INotifyPropertyChanged 接口都不可用,WPF 使用 ValueChanged 事件。 此行为涉及到与属性 P 相对应的 PropertyDescriptor 对象上调用 PropertyDescriptor.AddValueChanged 方法。 遗憾的是,此操作会导致公共语言运行库 (CLR) 可以创建从此 PropertyDescriptor 对象 X 的强引用。 CLR 还保留全局表中的 PropertyDescriptor 对象的引用

public class CustomCollectionClass : INotifyPropertyChanged
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: