关于WPF中MVVM模式被滥用导致维护成本高的问题,确实存在以下关键现象和解决方案:
滥用现象分析:
MVVM被强制应用于简单界面场景,导致代码量激增且可读性下降,项目过度分层,ViewModel与Model的间接调用增加了调试复杂度,开发团队盲目追求模式统一,忽视实际业务场景需求
典型维护痛点:
① 数据绑定链路过长时,属性变更通知(INotifyPropertyChanged)调试困难
② 命令层(ICommand)与业务逻辑过度耦合,单元测试成本上升
③ 嵌套View的ViewModel重构频率高,影响迭代效率
如果应用程序需要实时绑定过多的数据,数据交互量大、频繁都不建议采用WPF的MVVM模式开发项目,MVVM 实际上会成为阻碍,因为它引入了减慢进程的抽象,并且假设我们现在正在讨论 WPF/Silverlight/WP7(而Silverlight和WP7早已被淘汰被开发者遗忘),绑定引擎目前不是那么高效;尤其开发周期紧张的短期项目避免使用造成超出成本预算,相反采用传统WPF正常窗体或Winfrom更好控制把握。
WPF 从未真正实现从数据绑定和 MVVM 到像 React & friends 那样基于组件 + 状态管理的架构的跨越。其后果就是一个过于复杂、混乱不堪、充满陷阱的绑定系统。但它仍然领先于时代——如果能再迈出最后一步,它就会变得无比出色。正因为无法迈出最后一步导致望而却步,开发后续维护代价成本高昂。
从各大英文社区反馈:微软创建几个没有任何改进的新框架,令人遗憾:现在微软只有几个维护不善、平庸无奇的框架,而不是一个真正优秀的框架。持续的更新也扼杀了许多开源项目。
MVVM 构建的 WPF 应用,开发到中后期陷入了诸如内存泄漏、紧耦合和框架怪癖等陷阱。
紧耦合 - View 默认其DataContext属于特定的 ViewModel 类型。更改 ViewModel 会导致 View 崩溃。
内存泄漏 -如果 View 持有对 ViewModel 的直接引用,则可能会延迟垃圾收集。
参考:Mastering MVVM in WPF C#- The Good, the Bad, and the Memory Leaks(https://medium.com/@lllsamod/mastering-mvvm-in-wpf-c-the-good-the-bad-and-the-memory-leaks-953a10331fbd)
MVVM框架内存问题参考:devexpress.com社区“MVVM Framework Memory Issues”地址:https://supportcenter.devexpress.com/ticket/details/t490362/mvvm-framework-memory-issues
……
In an attempt to try and track down the problem I downloaded the AdventureWorks2014 database and created a new project against it.
I built a EF v6 model from the database, choosing all table schemas except dbo, and then used the scaffolding wizard to create the Outlook Inspired views and models.
Running this application demonstrates much the same behaviour I am experiencing so am asking for some help and guidance.
If I move between the views and watch the memory using a profiler the memory steadily goes up and up until it reaches a point where all the views must be in memory and the memory usage levels out. Depending on the size of an application this could be unacceptable. This project levels out at about 750mb of memory.
I have tried modifying the DocumentViewModel class and commented out the line in the CreateDocument method that set the DestroyOnClose property for the document to false. This unfortunately had next to no effect.
I then used the built in theme selector in the application to change from the default DX theme to Metropolis Dark. Once I started moving around again the memory usage once again started to rise. Moving between a few views and the memory usage and topped the 1gb.
……
对译“
我在使用 mvvm 脚手架向导构建的应用程序中遇到了一个问题,即视图模型被保留在内存中并且从未被释放。
为了尝试追踪问题,我下载了 AdventureWorks2014 数据库并针对它创建了一个新项目。
我从数据库构建了一个 EF v6 模型,选择了除 dbo 之外的所有表模式,然后使用脚手架向导创建了 Outlook Inspired 视图和模型。
运行此应用程序表现出与我所经历的行为相同的行为,因此请求一些帮助和指导。
如果我在视图之间移动,并使用分析器观察内存使用情况,内存会稳步上升,直到所有视图都必须占用内存,内存使用量才会趋于平稳。根据应用程序的大小,这可能是不可接受的。这个项目的内存使用量大约为 750MB。
我尝试修改 DocumentViewModel 类,并注释掉 CreateDocument 方法中将文档的 DestroyOnClose 属性设置为 false 的那一行。但不幸的是,这几乎没有效果。
然后,我使用应用程序内置的主题选择器,将默认的 DX 主题更改为 Metropolis Dark。当我再次开始移动屏幕时,内存占用再次开始上升。在几个视图之间切换时,内存占用超过了 1GB。
”无法释放内存回收,注定处理数据效率拥堵缓慢,当数据越大,窗体越多时注定卡死,异常频发极大降低程序性能。