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?
Using
Dispatcher.CurrentDispatcheris wrong anyway. It would create a new Dispatcher for a (background) thread that does not already have one. See here:That is not what you want. Use
Application.Current.Dispatcheror somehow pass the UI Dispatcher to the view model as parameter.However, assuming you call
from the UI thread, you do not need a Dispatcher call at all. This code should be sufficient: