WPF not disposing viewmodel

63 Views Asked by At

I am having an issue of memory leaks regarding WPF. I have a view model that is not being disposed.

I narrowed the problem to a method that is calling the database and updating the fields on the viewModel.

It goes like this:

public async Task RefreshAsync2(CancellationToken token = default)
{
        var data = await Mediator.Send(new GetDataQuery());

        if (data != null)
        {
            Dispatcher.CurrentDispatcher.Invoke(() => {
                ViewModelInfo = data;
            });
        }
}

And in this method the problem lies in the Dispatcher.CurrentDispatcher.Invoke that is using an anonymous (lambda) method to capture "this".

I have to use Dispatcher because this refresh method could be called from another thread ie. a Timer.

How to get rid of this?

1

There are 1 best solutions below

6
Clemens On

Using Dispatcher.CurrentDispatcher is wrong anyway. It would create a new Dispatcher for a (background) thread that does not already have one. See here:

Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.

That is not what you want. Use Application.Current.Dispatcher or somehow pass the UI Dispatcher to the view model as parameter.

However, assuming you call

await RefreshAsync2();

from the UI thread, you do not need a Dispatcher call at all. This code should be sufficient:

public async Task RefreshAsync2(CancellationToken token = default)
{
    var data = await Mediator.Send(new GetDataQuery());
    if (data != null)
    {
        ViewModelInfo = data;
    }
}