MVVM更容易内存泄露吗?

由于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的界面是这样子的:

image

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模式实现的,看看有内存泄露:

image

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没有关系。

2011-09-01 16h22_58

 

深入思考和继续阅读

通常.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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/475493.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

分组统计 - 不同时间颗粒度下,按照秒、分、时、日、周、月、季度、年 GROUP BY 分组统计 - (MySQL)

数据处理时&#xff0c;经常需要&#xff1a;统计不同时间粒度下的数据分布情况。 例如&#xff0c;网站每天&#xff08;or每小时&#xff09;的访问量&#xff0c;周杰伦每年&#xff08;or每季度 or每月&#xff09;的收入等。 首先有一个表叫&#xff1a;table_test&…

LeetCode 971. 翻转二叉树以匹配先序遍历(DFS)

1. 题目 给定一个有 N 个节点的二叉树&#xff0c;每个节点都有一个不同于其他节点且处于 {1, …, N} 中的值。 通过交换节点的左子节点和右子节点&#xff0c;可以翻转该二叉树中的节点。 考虑从根节点开始的先序遍历报告的 N 值序列。将这一 N 值序列称为树的行程。 &…

初学Struts遇到的坑爹问题

主要页面 Action: LoginAction.java //用于处理登陆这个事件 FromBean: LoginForm.java //存储Login.jsp中传过来的表单内容 JSP:Login.jsp //登陆页面&#xff0c;提交到login.do XML配置文件&#xff1a;struts-config.xml&#xff0c;web.x…

缺失值处理 - 获取一段时间内所有日期的列表 - (Python、MySQL)

有的时候做数据清洗的时候 &#xff0c; 如果表中数据在某一天没有记录&#xff0c;但是业务要求不能有缺失日期&#xff0c;那么就需要我们将这些缺失日期补上。这个前提就是我们先要有一张包含所有日期的列表&#xff08;作为左表&#xff09;&#xff0c;供我们进行匹配&…

[Kaggle] Digit Recognizer 手写数字识别

文章目录1. Baseline KNN2. Try SVCDigit Recognizer 练习地址 相关博文&#xff1a;[Hands On ML] 3. 分类&#xff08;MNIST手写数字预测&#xff09; 1. Baseline KNN 读取数据 import pandas as pd train pd.read_csv(train.csv) X_test pd.read_csv(test.csv)特征、…

C#中的类型转换大总结

使用C#一个最常见的问题便是各种类型间的转换。我们知道&#xff0c;C#中的类型分为值类型和引用类型两大类。但是&#xff0c;有关它们间各自转换的细节描述在网上很少得到详细的回答。现在&#xff0c;我结合搜索到的部分资料整理如下&#xff1a; 1&#xff0c;问题 c#中类型…

DataFrame字符串之分割split()、清洗drop()、合并concat()、重新建立索引reset_index() - (Python)

数据建模之前&#xff0c;我们从数据部门拿到数据&#xff0c;但是这些数据的格式往往并不是我们可以直接使用的&#xff0c;比如下面表中的数据&#xff08;左&#xff1a;原数据格式&#xff09;。 原数据格式id自成一列&#xff0c;这个很好&#xff0c;但是标签和标签的置…

LeetCode 97. 交错字符串(DP)

1. 题目 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。 示例 1: 输入: s1 "aabcc", s2 "dbbca", s3 "aadbbcbcac" 输出: true示例 2: 输入: s1 "aabcc", s2 "dbbca", s3 "aadbbbaccc&qu…

浅谈 JavaScript 编程语言的编码规范--转载

原文&#xff1a;http://www.ibm.com/developerworks/cn/web/1008_wangdd_jscodingrule/ 对于熟悉 C/C 或 Java 语言的工程师来说&#xff0c;JavaScript 显得灵活&#xff0c;简单易懂&#xff0c;对代码的格式的要求也相对松散。很容易学习&#xff0c;并运用到自己的代码中。…

Power BI 数据分析可视化软件入门教程

入 门 l Power BI 的引导学习 什么是Power BI&#xff1f; Power BI 是软件服务、应用和连接器的集合&#xff0c;它们协同工作以将相关数据来源转换为连贯的视觉逼真的交互式见解。 Power BI 简单且快速&#xff0c;能够从 Excel 电子表格或本地数据库创建快速见解。同…

分组统计 - DataFrame.groupby() 所见的各种用法 - Python代码

目录 所见 1 &#xff1a;日常用法 所见 2 &#xff1a;解决groupby.sum() 后层级索引levels上移的问题 所见 3 &#xff1a;解决groupby.apply() 后层级索引levels上移的问题 所见 4 &#xff1a;groupby函数的分组结果保存成DataFrame groupby的函数定义&#xff1a; Da…

LeetCode 1486. 数组异或操作

1. 题目 给你两个整数&#xff0c;n 和 start 。 数组 nums 定义为&#xff1a;nums[i] start 2*i&#xff08;下标从 0 开始&#xff09;且 n nums.length 。 请返回 nums 中所有元素按位异或&#xff08;XOR&#xff09;后得到的结果。 示例 1&#xff1a; 输入&#…

C 内存管理详解

程序员们经常编写内存管理程序&#xff0c;往往提心吊胆。如果不想触雷&#xff0c;唯一的解决办法就是发现所有潜伏的地雷并且排除它们&#xff0c;躲是躲不了的。本文的内容比一般教科书的要深入得多&#xff0c;读者需细心阅读&#xff0c;做到真正地通晓内存管理。   1、…

对照表 - 用心整理了一批国内省份、城市、县城的对照表,用于匹配,拿走不谢

采集的数据中&#xff0c;企业注册地址往往都是城市名&#xff0c;如果你想知道这些企业分布的省份&#xff0c;那么就需要这样一张对照表。 文件存储位置&#xff1a; 百度网盘链接: https://pan.baidu.com/s/1T8aobyzXRRvDQ0NjcEBCUw 提取码: cm7g 以下是文件中的前 100 …

js 获取url的get传值函数

最进在做瞎干项目时用到的&#xff0c;发上了备用&#xff0c;主要是用的正则匹配&#xff01; function getvl(name) {var reg new RegExp("(^|\\?|&)" name "([^&]*)(\\s|&|$)", "i");if (reg.test(location.href)) return unes…

LeetCode 1487. 保证文件名唯一(哈希map)

1. 题目 给你一个长度为 n 的字符串数组 names 。你将会在文件系统中创建 n 个文件夹&#xff1a;在第 i 分钟&#xff0c;新建名为 names[i] 的文件夹。 由于两个文件 不能 共享相同的文件名&#xff0c;因此如果新建文件夹使用的文件名已经被占用&#xff0c;系统会以 (k) …

线性回归 - 多元线性回归案例 - 分析步骤、输出结果详解、与Python的结果对比 -(SPSS建模)

现在用 Python 写线性回归的博客都快烂大街了&#xff0c;为什么还要用 SPSS 做线性回归呢&#xff1f;这就来说说 SPSS 存在的原因吧。 SPSS 是一个很强大的软件&#xff0c;不用编程&#xff0c;不用调参&#xff0c;点巴两下就出结果了&#xff0c;而且出来的大多是你想要的…

LeetCode 1488. 避免洪水泛滥(贪心+set二分查找)

1. 题目 你的国家有无数个湖泊&#xff0c;所有湖泊一开始都是空的。 当第 n 个湖泊下雨的时候&#xff0c;如果第 n 个湖泊是空的&#xff0c;那么它就会装满水&#xff0c;否则这个湖泊会发生洪水。 你的目标是避免任意一个湖泊发生洪水。 给你一个整数数组 rains &#xf…

R12 应付款模块(AP):预付款(prepayment)的标准处理流程

预付款的概念 财务会计的解释&#xff1a; 企业对于某些物资有时需要采取预先订购的方式&#xff0c;即按照购货合同规定预付一部分货款。这部分预先付给供货单位的订货款就构成了企业的预付账款。&#xff08;来自会计学概论&#xff0c;要区分定金和预付款的区别&#xff01;…

Python连接MySQL数据库(pymysql),DataFrame写入 MySQL(create_engine)- Python代码

模块安装 使用以下命令安装 PyMySQL&#xff1a; $ pip install PyMySQL 若系统不支持 pip&#xff0c;还可以这样安装&#xff1a; $ git clone https://github.com/PyMySQL/PyMySQL $ cd PyMySQL/ $ python3 setup.py install Python连接MySQL数据库 # -*- coding:utf-8…