title: Disposing a timer inside a ViewModel, upon closing the main window
body: <p>Currently in my application, I have a <code>RelayCommand</code> which calls an action which starts a <code>Timer</code>. I have a separate command which the calls the <code>Dispose()</code> method to get rid of/release the timer. This all sits in the ViewModel counterpart of the project.</p>
  
  <p>Using the MVVM pattern, how would I dispose of this <code>Timer</code> upon closing the window, as well as carrying out the regular/default operation of closing the window?</p>
  
  <p>I am also using the MVVM-Light toolkit, if this is of any help.</p>
  
  <p>An example of my current solution is shown below:</p>
  
  <h2>ViewModel</h2>
  
  <pre><code>private static Timer dispatchTimer;
  
  public MainViewModel()
  {
      this.StartTimerCommand = new RelayCommand(this.StartTimerAction);
      this.StopTimerCommand = new RelayCommand(this.StopTimerAction);
  }
  
  public RelayCommand StartTimerCommand { get; private set; }
  public RelayCommand StopTimerCommand { get; private set; }
  
  private void StartTimerAction()
  {
      dispatchTimer = new Timer(new TimerCallback(this.IgnoreThis), null, 0, 15);
  }
  
  private void StopTimerAction()
  {
      dispatchTimer.Dispose();
  }
  </code></pre>
  
  <h2>View (xaml)</h2>
  
  <pre><code>....
  Height="896"
  Width="1109"
  DataContext="{Binding Main, Source={StaticResource Locator}}"&gt;
  
      &lt;Grid x:Name="mainGrid"
            Width="Auto"
            Height="Auto"&gt;              
            &lt;Button x:Name="startTimerButton"
                    Content="Start Timer"
                    Command="{Binding StartTimerCommand}"/&gt;
             &lt;Button x:Name="stopTimerButton"
                     Content="Stop Timer"
                     Command="{Binding StopTimerCommand}"/&gt;
      &lt;/Grid&gt;
  
  &lt;/Window&gt;
  </code></pre>
  
  <h2>View (Code-Behind)</h2>
  
  <pre><code>public MainWindow()
  {
      this.InitializeComponent();
  
      //Would a 'Closing +=' event be called here?
  }
  </code></pre>