Memory leak in WPF app due to DelegateCommand

前端 未结 3 1790
轮回少年
轮回少年 2021-02-20 08:24

I just finished desktop apps written in WPF and c# using MVVM pattern. In this app I used Delegate Command implementation to wrap the ICommands properties exposed in my ModelVie

3条回答
  •  失恋的感觉
    2021-02-20 09:13

    In your case, what contains a reference to what?

    1. DelegateCommand contains a reference to ViewModel - its execute and canExecute properties contain references to a methods of the ViewModel instance.

    2. ViewModel contains a reference to DelegateCommand - its PrintCommand property.

    3. The view contains any number of references to the ViewModel.

    4. The CommandManager contains a reference to DelegateCommand in its RequerySuggested event.

    That last reference is a special case: CommandManager uses a WeakReference in its RequerySuggested event, so despite the fact that DelegateCommand registers for that event, it can still be garbage-collected.

    Given all this, you shouldn't be having a problem. If the view gets disposed, neither the ViewModel nor the DelegateCommand should be reachable.

    You say you've profiled the application and DelegateCommand is holding a reference to ViewModel. It seems to me that the logical next question should be: what's holding a reference to DelegateCommand? It shouldn't be CommandManager. Do you have something else in your application that's referencing your commands?

提交回复
热议问题