由于MVVM是把View, ViewModel, Model紧紧绑定在一起的模式,特别视图和视图模型通过实现观察者模式双向绑定和NotifyPropertyChanged事件,似乎更加容易造成内存泄露/内存不释放。网上也有这种说法。真的是这样的吗?我们来实际测试一下。

实际测试MVVM是不是容易内存泄露

为了说明问题,我把MVVM搞复杂一点,在ViewModel里面引用一个Singleton单例模式的Service,这个Service定义如下:

   1: namespace SilverlightApplication1.Service
   2: {
   3:     public class GlobalService
   4:     {
   5:         private static readonly GlobalService Instance = new GlobalService();
   6:  
   7:         static GlobalService()
   8:         {
   9:         }
  10:  
  11:         public static GlobalService GetInstance()
  12:         {
  13:             return Instance;
  14:         }
  15:     }
  16: }

写一个ViewModel,里面引用了Service,用到了ICommand,实现了INotifyPorpertyChanged接口:

   1: using System.ComponentModel;
   2: using System.Windows.Input;
   3: using SilverlightApplication1.Service;
   4:  
   5: namespace SilverlightApplication1.MVVM
   6: {
   7:     public class ViewModel1 : INotifyPropertyChanged
   8:     {
   9:         private GlobalService _injectSingletonService;
  10:  
  11:         public ViewModel1(GlobalService injectSingletonService)
  12:         {
  13:             Property1 = "test1";
  14:             Command1 = new DelegateCommand(LoadMe, CanLoadMe);
  15:  
  16:             _injectSingletonService = injectSingletonService;
  17:         }
  18:  
  19:         private string _property1;
  20:         public string Property1
  21:         {
  22:             get { return _property1; }
  23:             set
  24:             {
  25:                 _property1 = value;
  26:  
  27:                 if (PropertyChanged != null)
  28:                 {
  29:                     PropertyChanged(this,
  30:                         new PropertyChangedEventArgs("Property1"));
  31:                 }
  32:             }
  33:         }
  34:         
  35:         public ICommand Command1 { get; set; }
  36:         public event PropertyChangedEventHandler PropertyChanged;   
  37:  
  38:         private void LoadMe(object param)
  39:         {
  40:             
  41:         }
  42:  
  43:         private bool CanLoadMe(object param)
  44:         {
  45:             return true;
  46:         }
  47:     }
  48: }

来一个视图View,绑定ViewModel,有个button绑定了ICommand,属性也绑定了。

   1: <UserControl x:Class="SilverlightApplication1.MVVM.View1"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:     mc:Ignorable="d"
   7:     d:DesignHeight="300" d:DesignWidth="400">
   8:     
   9:     <Grid x:Name="LayoutRoot" Background="White">
  10:         <TextBlock Height="65" HorizontalAlignment="Left" Margin="57,82,0,0" Name="textBlock1" Text="this is view1" VerticalAlignment="Top" Width="224" FontSize="18" />
  11:         <Button Content="Button" Command="{Binding Command1}" Height="28" HorizontalAlignment="Left" Margin="55,130,0,0" Name="button1" VerticalAlignment="Top" Width="111" />
  12:         <TextBlock Height="28" HorizontalAlignment="Left" Margin="56,173,0,0" Name="textBlock2" Text="{Binding Property1}" VerticalAlignment="Top" Width="114" />
  13:     </Grid>
  14: </UserControl>

这个View1的界面是这样子的:

View1.xaml.cs代码:

   1: using System.Windows.Controls;
   2: using SilverlightApplication1.Service;
   3:  
   4: namespace SilverlightApplication1.MVVM
   5: {
   6:     public partial class View1 : UserControl
   7:     {
   8:         public View1()
   9:         {
  10:             InitializeComponent();
  11:  
  12:             this.DataContext = new ViewModel1(GlobalService.GetInstance());
  13:         }
  14:     }
  15: }

辅助类DelegateCommand源码:

   1: using System;
   2: using System.Windows.Input;
   3:  
   4: namespace SilverlightApplication1
   5: {
   6:     public class DelegateCommand : ICommand
   7:     {
   8:         public event EventHandler CanExecuteChanged;
   9:  
  10:         Func<object, bool> canExecute;
  11:         Action<object> executeAction;
  12:         bool canExecuteCache;
  13:  
  14:         public DelegateCommand(Action<object> executeAction,
  15:         Func<object, bool> canExecute)
  16:         {
  17:             this.executeAction = executeAction;
  18:             this.canExecute = canExecute;
  19:         }
  20:  
  21:         #region ICommand Members
  22:  
  23:         /// <summary>
  24:  
  25:         /// Defines the method that determines whether the command 
  26:  
  27:         /// can execute in its current state.
  28:  
  29:         /// </summary>
  30:  
  31:         /// <param name="parameter">
  32:  
  33:         /// Data used by the command. 
  34:  
  35:         /// If the command does not require data to be passed,
  36:  
  37:         /// this object can be set to null.
  38:  
  39:         /// </param>
  40:  
  41:         /// <returns>
  42:  
  43:         /// true if this command can be executed; otherwise, false.
  44:  
  45:         /// </returns>
  46:  
  47:         public bool CanExecute(object parameter)
  48:         {
  49:  
  50:             bool tempCanExecute = canExecute(parameter);
  51:  
  52:  
  53:  
  54:             if (canExecuteCache != tempCanExecute)
  55:             {
  56:  
  57:                 canExecuteCache = tempCanExecute;
  58:  
  59:                 if (CanExecuteChanged != null)
  60:                 {
  61:  
  62:                     CanExecuteChanged(this, new EventArgs());
  63:  
  64:                 }
  65:  
  66:             }
  67:  
  68:  
  69:  
  70:             return canExecuteCache;
  71:  
  72:         }
  73:  
  74:  
  75:  
  76:         /// <summary>
  77:  
  78:         /// Defines the method to be called when the command is invoked.
  79:  
  80:         /// </summary>
  81:  
  82:         /// <param name="parameter">
  83:  
  84:         /// Data used by the command. 
  85:  
  86:         /// If the command does not require data to be passed, 
  87:  
  88:         /// this object can be set to null.
  89:  
  90:         /// </param>
  91:  
  92:         public void Execute(object parameter)
  93:         {
  94:  
  95:             executeAction(parameter);
  96:  
  97:         }
  98:  
  99:         #endregion
 100:     }
 101: }

MainPage的代码:

   1: <UserControl x:Class="SilverlightApplication1.MainPage"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:     mc:Ignorable="d"
   7:     d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
   8:  
   9:     <Grid x:Name="LayoutRoot" Background="White">
  10:         <Button Content="Add view" Height="36" HorizontalAlignment="Left" Margin="20,31,0,0" Name="button1" VerticalAlignment="Top" Width="115" Click="button1_Click" />
  11:         <sdk:TabControl Height="197" HorizontalAlignment="Left" Margin="28,82,0,0" Name="tabControl1" VerticalAlignment="Top" Width="346">
  12:             <sdk:TabItem Header="tabItem1" Name="tabItem1">
  13:                 <Grid />
  14:             </sdk:TabItem>
  15:         </sdk:TabControl>
  16:         <Button Content="Close view" Height="35" HorizontalAlignment="Left" Margin="148,32,0,0" Name="button2" VerticalAlignment="Top" Width="108" Click="button2_Click" />
  17:     </Grid>
  18: </UserControl>

MainPage界面,主要是在Tab里面打开View1,不断打开关闭,打开关闭,因为View1是用MVVM模式实现的,看看有内存泄露:

MainPage.xaml.cs,就是测试代码,正常情况下点击关闭tab,可能GC不会立即回收内存,这里为了便于测试,手动加了GC.Collect。(正常情况下,不推荐使用GC.Collect())

   1: using System;
   2: using System.Windows;
   3: using System.Windows.Controls;
   4: using SilverlightApplication1.MVVM;
   5:  
   6: namespace SilverlightApplication1
   7: {
   8:     public partial class MainPage : UserControl
   9:     {
  10:         public MainPage()
  11:         {
  12:             InitializeComponent();
  13:         }
  14:  
  15:         private void button1_Click(object sender, RoutedEventArgs e)
  16:         {
  17:             var v = new View1();
  18:             TabItem t = new TabItem {Content = v, Header = "header " + DateTime.Now.Second.ToString()};
  19:             this.tabControl1.Items.Add(t);
  20:         }
  21:  
  22:         private void button2_Click(object sender, RoutedEventArgs e)
  23:         {
  24:             this.tabControl1.Items.RemoveAt(0);//view1, viewModel1并没有立即释放,由GC决定何时决定。
  25:  
  26:             System.GC.Collect();
  27:             System.GC.WaitForPendingFinalizers();
  28:  
  29:             //{
  30:             //    FooContext context = new FooContext();
  31:             //    context.Load(context.MyQuery);
  32:             //}
  33:         }
  34:     }
  35: }

测试结果:内存泄露和MVVM无关

我的测试结果是内存能够释放,没有内存泄露问题,也就是说MVVM模式和内存泄露无关。那种所谓的MVVM更容易内存泄露的说法没有什么道理。但不排除你的ViewModel和Model里面有复杂的引用关系,比如你的VIewModel或者Model引用了其他的类,你可能没有察觉,而那些类可能是Public Static的(是GC Root,不释放),或者是永远不释放的(如MainForm)引用,那就复杂了。由于你的ViewModel被那些不释放的对象引用着,而你却不知道,那就是内存泄露了。这和MVVM没有关系。

深入思考和继续阅读

通常.NET程序的内存泄露原因:

  • Static references
  • Event with missing unsubscription
  • Static event with missing unsubscription
  • Dispose method not invoked
  • Incomplete Dispose method

有关如何避免.NET程序的内存泄露,请仔细阅读MSDN这两篇文章,详细讲述了<如何检测.NET程序内存泄露>以及<如何写高性能的托管程序>

  • How to detect and avoid memory and resources leaks in .NET applications
  • Writing High-Performance Managed Applications : A Primer

有关.NET的自动内存管理机制、GC机制,垃圾回收原理等深层次内容,请仔细阅读下面的内容:

  • 买书《CLR Via C#(3rd Edition)》,里面有《Memory Management》这一章专门讲述了.NET CLR的自动内存管理和垃圾回收机制
  • CodeProject上的文章《Memory Management Misconceptions》有助你深入理解Root, Generation 0, 1…

@:Mainz → http://www.cnblogs.com/Mainz 
®: 博文是本人当时的学习笔记及知识整理,由于自身局限错误在所难免,敬请斧正. 博文中源码只作为例子学习参考之用,不保证能运行,对后果不负任何责且无任何质保,如有不明请给我留言 
©: 本文版权属于博客园和本人,版权基于署名 2.5 中国大陆许可协议发布,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接和署名Mainz(包含链接),不得删节,否则保留追究法律责任的权利。

分类: SilverLight

转载于:https://www.cnblogs.com/Areas/archive/2011/09/23/2186621.html

MVVM更容易内存泄露吗?相关推荐

  1. 在Ubuntu 14.04 64bit上安装Valgrind并检查内存泄露

    valgrind官网:http://valgrind.org/ 1.安装方法 第一种方式:下载目前最新的源码,编译安装,在服务器上推荐这种方式 wget http://valgrind.org/dow ...

  2. ATS插件开发中内存泄露问题的解决方法探讨

    接触ATS开发已经有几年了,开发过内核的模块,也从事过插件的开发.内存泄露问题一直是一个困扰大多数ATS开发者的头疼的问题,下面说说我自己的感受和思考.这里这关注ATS插件开发这个话题.源码的exam ...

  3. Ubuntu下内存泄露检测工具Valgrind的使用

    在VS中可以用VLD检测是否有内存泄露,可以参考http://blog.csdn.net/fengbingchun/article/details/44195959,下面介绍下Ubuntu中内存泄露检 ...

  4. Java String.substring内存泄露?

    2019独角兽企业重金招聘Python工程师标准>>> String可以说是最常用的Java类型之一了,但是最近听说JDK6里面String.substring存在内存泄露的bug, ...

  5. Qt浅谈之一:内存泄露(总结)

    一.简介        Qt内存管理机制:Qt 在内部能够维护对象的层次结构.对于可视元素,这种层次结构就是子组件与父组件的关系:对于非可视元素,则是一个对象与另一个对象的从属关系.在 Qt 中,在 ...

  6. C++ 检测内存泄露

    本文描述了如何检测内存泄露.最主要的是纯C,C++的程序如何检测内存泄露. 现在有很多专业的检测工具,比如比较有名的BoundsCheck, 但是这类工具也有他的缺点,我认为首先BoundsCheck ...

  7. 网络瓶颈、线程死锁、内存泄露溢出、栈堆、ajax

    网络瓶颈:网络传输性能及稳定性的一些相关元素 线程死锁:多个线程因竞争资源造成的一种僵局 下面我们通过一些实例来说明死锁现象. 先看生活中的一个实例,2个人一起吃饭但是只有一双筷子,2人轮流吃(同时拥 ...

  8. 如何使用Eclipse内存分析工具定位内存泄露

    本文以我司生产环境Java应用内存泄露为案例进行分析,讲解如何使用Eclipse的MAT分析定位问题 一. 背景 11月10号晚上8点收到报警邮件,一看是OOM 打开公司监控系统查看应用各项指标发现J ...

  9. Netty堆外内存泄露排查与总结

    导读 Netty 是一个异步事件驱动的网络通信层框架,用于快速开发高可用高性能的服务端网络框架与客户端程序,它极大地简化了 TCP 和 UDP 套接字服务器等网络编程. Netty 底层基于 JDK ...

最新文章

  1. linux之find -regex 使用正则表达式
  2. 【网址收藏】podman安装及使用简单介绍
  3. 二叉树的层序遍历 IIPython解法
  4. (八)限定某个目录禁止解析php、限制user_agent和PHP相关配置
  5. leetcode 941. 有效的山脉数组
  6. python安装插件报错原因_Sublime Text3 python自动补全问题——Sublime Text3安装Anaconda插件...
  7. centos中bash占用cpu,Linux中显示内存和CPU使用率最高的进程和SHELL脚本例子
  8. JavaScript正则表达式简明教程(二)
  9. 在网页中加入神奇的效果
  10. RN学习(一)——创建第一个RN项目
  11. 【UVA10129】Play on Words(欧拉回路+有向图连通性判断+打印欧拉道路)
  12. 设置下载安装 桌面_电脑C盘快满了不要慌,别只知道清垃圾,这些设置也要改...
  13. 纪录片《Code Rush》
  14. 关于“无穷”的概念---数学笔记“无穷”
  15. SE 的 ONNX 图
  16. 自托管 NodeJS ChatGPT Discord 机器人
  17. RTX2080+CUDA11.7+CUDNN8.6.0+ubuntu20.04+python3.8.10 部署和安装
  18. Transaction Processing on Modern Hardware 读书笔记
  19. 给中国学生的第五封信
  20. 机器学习、神经网络PPT作图素材

热门文章

  1. Android的TextView在显示文字的时候,如果有段中文有英文,有中文,有中文标点符号,你会发现,当要换行的时候遇到中文标点, 这一行就会空出很多空格出来...
  2. 云栖科技评论第48期:前沿科技对世界的改造 我们这代人只完成了1%
  3. 通过Yeoman快速搭建AngularJS webapp应用的实践
  4. Compile a native C Android application
  5. ASP.NET MVC3 异步刷新
  6. 【2022】JVM常见面试真题详解
  7. 打印hello world java_java – 如何打印“hello world”?
  8. Flask 第三方组件之 script
  9. pycharm Debug问题
  10. matlab var std,Matlab var std cov 函数解析