WPF ViewModel GC

I have a ViewModel that, when receiving an event from the model, shows a dialog to the user by opening the ViewModel dialog and passing it to the data binding dialog, i.e.

public class MainViewModel
{
    ...
    private void OnModelRaisedEvent(object sender, EventArgs e)
    {
        DialogViewModel dialogViewModel = new DialogViewModel();
        Window dialog = new DialogView(dialogViewModel);
        dialog.ShowDialog();
    }
 }

      

In the dialog box, I am connecting to a button to close the window, i.e.

public class DialogView : Window
{
    public DialogView(DialogViewModel viewModel)
    {
        InitializeComponent();
        Loaded += (s,e) => {DataContext = viewModel; };
    }

    ...

    private void ButtonOnClick(object sender, RoutedEventArgs e)
    {
        Close();
    }
 }

      

Since only DialogView uses the DialogViewModel, can I be sure there is no memory leak here?

For example, if I open and close the dialog multiple times, will the DialogViewModel get GC'd when the DialogView is closed so as not to accumulate multiple DialogViewModel instances. Observed memory usage in Task Manager and it grows when DialogView is opened and closed multiple times, but not sure if this has to do with GC just not pushed.

+3


source to share


1 answer


You actually have dependency injection right now, as you are injecting the viewmodel into the dialog via the constructor.

While the dialog is running, it contains a link to dialogViewModel

in MainViewModel

.



When you close the dialog, the control returns to the method OnModelRaisedEvent

, and immediately after that, the method ends (there is no other code after dialog.ShowDialog()

), and the GC collects the variable dialogViewModel

since its scope is limited by this method.

So bottom line: you can use your code without issue.

+3


source







All Articles