Memory leak in WPF app due to DelegateCommand

前端 未结 3 1716
轮回少年
轮回少年 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:28

    I think that in this code there is a circular reference which is causing the ViewModel to never be garbage collected.

    I know this is an old question, but I will point out that some implementations of DelegateCommand or RelayCommand hold a WeakReference to the action. Your use of the DelegateCommand here is typical, but unfortunately will cause memory leaks with this implementation because when the ViewModel's method is passed into the DelegateCommand's constructor, a reference to the class containing that method is automatically captured by the delegate.

    If you implemented IDispose on your ViewModel and cleared the references to the DelegateCommands explicitly in Dispose, then you could continue to use this implementation. Your view that's constructing your ViewModel would also have to Dipose of it, however.

提交回复
热议问题