WPF-动态与静态资源 [英] WPF - Dynamic vs Static Resources

查看:152
本文介绍了WPF-动态与静态资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF项目中遇到了巨大的内存泄漏,并试图弄清楚如何最大程度地减少内存泄漏.要访问资源,我有100%的时间使用StaticResource.我应该在可能的地方使用DynamicResource吗?就StaticResource和DynamicResource之间的内存管理而言,是否有优势?

I am experiencing an enormous memory leak in my WPF project and am trying to figure out what I can do to minimize it. To access resources I use StaticResource 100% of the time. Should I use DynamicResource where I can? Are there advantages as far as memory management between StaticResource and DynamicResource?

仅供参考:我有一个列表框,它通过DataTemplate显示数据.随着用户向上/向下滚动,内存快速增加,仅在向上/向下滚动的几分钟内就达到了1GB.

FYI: I have a listbox showing data via a DataTemplate. As the user scrolls up/down memory increases fast, reaching 1GB in just a couple of minutes of scrolling up/down.

推荐答案

这不太可能是StaticResource/DynamicResource.静态和动态指的是查找策略,而不是保留策略:

This is unlikely to be a StaticResource / DynamicResource thing. Static and dynamic refer to lookup strategies, not retention strategies:

  • StaticResource的意思是查找 资源一次,然后继续使用 相同的值."

  • StaticResource means "look up the resource once, then just keep using the same value."

DynamicResource的意思是查找 每次需要的资源 如果值已更改."

DynamicResource means "look up the resource each time it's needed, in case the value has changed."

因此,您所做的一切听起来正确:将StaticResource用于不变的资源(例如DataTemplates)(并将DynamicResource保留给可能更改的资源,例如,如果用户更改系统颜色方案可能会更改的系统画笔).通过StaticResource引用分配DataTemplate所花费的内存不会比通过DynamicResource引用分配DataTemplate多,并且长期使用会更便宜,因为WPF不必一直返回并重新评估该引用.

What you are doing therefore sounds correct: use StaticResource for unchanging resources such as DataTemplates (and reserve DynamicResource for resources that may change, such as system brushes that might change if the user changes the system colour scheme). The allocation of the DataTemplate via the StaticResource reference will cost no more memory than allocating it via a DynamicResource reference, and long term will be cheaper because WPF doesn't have to keep going back and re-evaluating the reference.

更有可能的是,您的模板本身正在执行某种操作,当应用模板(在数据项上实例化)时,该模板正在以泄漏的方式分配内存(或间接导致分配内存).我看到的一个与直觉相反的原因是模板是否使用旧式位图效果.另一个是如果模板调用了隐藏事件处理程序的代码隐藏.但是,您引用模板资源的方式都可能不会影响这些.

What is more likely is that your template itself is doing something which, when the template is applied (instantiated on a data item), is allocating memory (or indirectly causing memory to be allocated) in a leaky way. One counterintuitive cause that I've seen for this is if the template uses old-style bitmap effects. Another is if the template invokes code-behind that hooks up event handlers. But neither of these is likely to be affected by the way you reference the template resource.

这篇关于WPF-动态与静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆