Memory leak in WPF app due to DelegateCommand

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

    After reading this post, I then came across a web page that had some relating information. It is a page on CodePlex called Memory Leak caused by DelegateCommand.CanExecuteChanged Event.

    Reported by : huetter
    Updated by : dschenkelman

    When profiling my application I noticed that plenty of EventHandlers had never been deregistered from DelegateCommand's CanExecuteChanged-Event. So those EventHandlers were never been garbage-collector, which caused a severe memory leak.

    As registering CanExecuteChanged-EventHandles is done outside application code scope I had expected them to be deregistered automatically as well. At this point I thought this might as well be a ThirdParty WPF control issue, but digging further I read a blog post stating that "WPF expects the ICommand.CanExecuteChanged-Event to apply WeakReferences for EventHandlers". I had a look into RoutedCommand, and noticed it uses WeakReferences as well.

    I adapted DelegateCommand to use an implementation similar to RoutedCommand's CanExecuteChanged-Event, and the memory leak was gone. The same is true for CompositeCommand.

    Closed Nov 3, 2009 at 6:28 PM by This issue was fixed in the Prism-v2.1 release, so the Workitem is closed now. Prism 2.1 can be downloaded from here:
    http://www.microsoft.com/downloads/details.aspx?FamilyID=387c7a59-b217-4318-ad1b-cbc2ea453f40&displaylang=en

提交回复
热议问题