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

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

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

namespace SilverlightApplication1.Service
   2: {
class GlobalService
   4:     {
new GlobalService();
   6:  
static GlobalService()
   8:         {
   9:         }
  10:  
static GlobalService GetInstance()
  12:         {
return Instance;
  14:         }
  15:     }
  16: }

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

using System.ComponentModel;
using System.Windows.Input;
using SilverlightApplication1.Service;
   4:  
namespace SilverlightApplication1.MVVM
   6: {
class ViewModel1 : INotifyPropertyChanged
   8:     {
private GlobalService _injectSingletonService;
  10:  
public ViewModel1(GlobalService injectSingletonService)
  12:         {
;
new DelegateCommand(LoadMe, CanLoadMe);
  15:  
  16:             _injectSingletonService = injectSingletonService;
  17:         }
  18:  
string _property1;
string Property1
  21:         {
return _property1; }
  23:             set
  24:             {
value;
  26:  
null)
  28:                 {
this,
));
  31:                 }
  32:             }
  33:         }
  34:         
public ICommand Command1 { get; set; }
event PropertyChangedEventHandler PropertyChanged;   
  37:  
object param)
  39:         {
  40:             
  41:         }
  42:  
object param)
  44:         {
true;
  46:         }
  47:     }
  48: }

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

>
   8:     
>
/>
/>
/>
>
>

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

MVVM更容易内存泄露吗?

View1.xaml.cs代码:

using System.Windows.Controls;
using SilverlightApplication1.Service;
   3:  
namespace SilverlightApplication1.MVVM
   5: {
class View1 : UserControl
   7:     {
public View1()
   9:         {
  10:             InitializeComponent();
  11:  
new ViewModel1(GlobalService.GetInstance());
  13:         }
  14:     }
  15: }

辅助类DelegateCommand源码:

using System;
using System.Windows.Input;
   3:  
namespace SilverlightApplication1
   5: {
class DelegateCommand : ICommand
   7:     {
event EventHandler CanExecuteChanged;
   9:  
bool> canExecute;
object> executeAction;
bool canExecuteCache;
  13:  
object> executeAction,
bool> canExecute)
  16:         {
this.executeAction = executeAction;
this.canExecute = canExecute;
  19:         }
  20:  
#region ICommand Members
  22:  
/// <summary>
  24:  
/// Defines the method that determines whether the command 
  26:  
/// can execute in its current state.
  28:  
/// </summary>
  30:  
  32:  
/// Data used by the command. 
  34:  
/// If the command does not require data to be passed,
  36:  
/// this object can be set to null.
  38:  
/// </param>
  40:  
/// <returns>
  42:  
/// true if this command can be executed; otherwise, false.
  44:  
/// </returns>
  46:  
object parameter)
  48:         {
  49:  
bool tempCanExecute = canExecute(parameter);
  51:  
  52:  
  53:  
if (canExecuteCache != tempCanExecute)
  55:             {
  56:  
  57:                 canExecuteCache = tempCanExecute;
  58:  
null)
  60:                 {
  61:  
new EventArgs());
  63:  
  64:                 }
  65:  
  66:             }
  67:  
  68:  
  69:  
return canExecuteCache;
  71:  
  72:         }
  73:  
  74:  
  75:  
/// <summary>
  77:  
/// Defines the method to be called when the command is invoked.
  79:  
/// </summary>
  81:  
  83:  
/// Data used by the command. 
  85:  
/// If the command does not require data to be passed, 
  87:  
/// this object can be set to null.
  89:  
/// </param>
  91:  
object parameter)
  93:         {
  94:  
  95:             executeAction(parameter);
  96:  
  97:         }
  98:  
#endregion
 100:     }
 101: }

MainPage的代码:

>
   8:  
>
/>
>
>
/>
>
>
/>
>
>

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

MVVM更容易内存泄露吗?

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

using System;
using System.Windows;
using System.Windows.Controls;
using SilverlightApplication1.MVVM;
   5:  
namespace SilverlightApplication1
   7: {
class MainPage : UserControl
   9:     {
public MainPage()
  11:         {
  12:             InitializeComponent();
  13:         }
  14:  
object sender, RoutedEventArgs e)
  16:         {
new View1();
 + DateTime.Now.Second.ToString()};
this.tabControl1.Items.Add(t);
  20:         }
  21:  
object sender, RoutedEventArgs e)
  23:         {
//view1, viewModel1并没有立即释放,由GC决定何时决定。
  25:  
  26:             System.GC.Collect();
  27:             System.GC.WaitForPendingFinalizers();
  28:  
//{
//    FooContext context = new FooContext();
//    context.Load(context.MyQuery);
//}
  33:         }
  34:     }
  35: }

 

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

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

MVVM更容易内存泄露吗?

 

深入思考和继续阅读

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

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

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

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

    Mainz(包含链接),不得删节,否则保留追究法律责任的权利。

    SilverLight

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

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

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

    namespace SilverlightApplication1.Service
       2: {
    class GlobalService
       4:     {
    new GlobalService();
       6:  
    static GlobalService()
       8:         {
       9:         }
      10:  
    static GlobalService GetInstance()
      12:         {
    return Instance;
      14:         }
      15:     }
      16: }

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

    using System.ComponentModel;
    using System.Windows.Input;
    using SilverlightApplication1.Service;
       4:  
    namespace SilverlightApplication1.MVVM
       6: {
    class ViewModel1 : INotifyPropertyChanged
       8:     {
    private GlobalService _injectSingletonService;
      10:  
    public ViewModel1(GlobalService injectSingletonService)
      12:         {
    ;
    new DelegateCommand(LoadMe, CanLoadMe);
      15:  
      16:             _injectSingletonService = injectSingletonService;
      17:         }
      18:  
    string _property1;
    string Property1
      21:         {
    return _property1; }
      23:             set
      24:             {
    value;
      26:  
    null)
      28:                 {
    this,
    ));
      31:                 }
      32:             }
      33:         }
      34:         
    public ICommand Command1 { get; set; }
    event PropertyChangedEventHandler PropertyChanged;   
      37:  
    object param)
      39:         {
      40:             
      41:         }
      42:  
    object param)
      44:         {
    true;
      46:         }
      47:     }
      48: }

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

    >
       8:     
    >
    />
    />
    />
    >
    >

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

    MVVM更容易内存泄露吗?

    View1.xaml.cs代码:

    using System.Windows.Controls;
    using SilverlightApplication1.Service;
       3:  
    namespace SilverlightApplication1.MVVM
       5: {
    class View1 : UserControl
       7:     {
    public View1()
       9:         {
      10:             InitializeComponent();
      11:  
    new ViewModel1(GlobalService.GetInstance());
      13:         }
      14:     }
      15: }

    辅助类DelegateCommand源码:

    using System;
    using System.Windows.Input;
       3:  
    namespace SilverlightApplication1
       5: {
    class DelegateCommand : ICommand
       7:     {
    event EventHandler CanExecuteChanged;
       9:  
    bool> canExecute;
    object> executeAction;
    bool canExecuteCache;
      13:  
    object> executeAction,
    bool> canExecute)
      16:         {
    this.executeAction = executeAction;
    this.canExecute = canExecute;
      19:         }
      20:  
    #region ICommand Members
      22:  
    /// <summary>
      24:  
    /// Defines the method that determines whether the command 
      26:  
    /// can execute in its current state.
      28:  
    /// </summary>
      30:  
      32:  
    /// Data used by the command. 
      34:  
    /// If the command does not require data to be passed,
      36:  
    /// this object can be set to null.
      38:  
    /// </param>
      40:  
    /// <returns>
      42:  
    /// true if this command can be executed; otherwise, false.
      44:  
    /// </returns>
      46:  
    object parameter)
      48:         {
      49:  
    bool tempCanExecute = canExecute(parameter);
      51:  
      52:  
      53:  
    if (canExecuteCache != tempCanExecute)
      55:             {
      56:  
      57:                 canExecuteCache = tempCanExecute;
      58:  
    null)
      60:                 {
      61:  
    new EventArgs());
      63:  
      64:                 }
      65:  
      66:             }
      67:  
      68:  
      69:  
    return canExecuteCache;
      71:  
      72:         }
      73:  
      74:  
      75:  
    /// <summary>
      77:  
    /// Defines the method to be called when the command is invoked.
      79:  
    /// </summary>
      81:  
      83:  
    /// Data used by the command. 
      85:  
    /// If the command does not require data to be passed, 
      87:  
    /// this object can be set to null.
      89:  
    /// </param>
      91:  
    object parameter)
      93:         {
      94:  
      95:             executeAction(parameter);
      96:  
      97:         }
      98:  
    #endregion
     100:     }
     101: }

    MainPage的代码:

    >
       8:  
    >
    />
    >
    >
    />
    >
    >
    />
    >
    >

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

    MVVM更容易内存泄露吗?

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

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using SilverlightApplication1.MVVM;
       5:  
    namespace SilverlightApplication1
       7: {
    class MainPage : UserControl
       9:     {
    public MainPage()
      11:         {
      12:             InitializeComponent();
      13:         }
      14:  
    object sender, RoutedEventArgs e)
      16:         {
    new View1();
     + DateTime.Now.Second.ToString()};
    this.tabControl1.Items.Add(t);
      20:         }
      21:  
    object sender, RoutedEventArgs e)
      23:         {
    //view1, viewModel1并没有立即释放,由GC决定何时决定。
      25:  
      26:             System.GC.Collect();
      27:             System.GC.WaitForPendingFinalizers();
      28:  
    //{
    //    FooContext context = new FooContext();
    //    context.Load(context.MyQuery);
    //}
      33:         }
      34:     }
      35: }

     

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

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

    MVVM更容易内存泄露吗?

     

    深入思考和继续阅读

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

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

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

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

      相关文章: