使用字体时 WPF TextBlock 内存泄漏 [英] WPF TextBlock memory leak when using Font
问题描述
我在 Windows 7 上使用 .NET 4.5,可能会发现内存泄漏.
我有一个 TextBlock
(不是 TextBox
- 这不是撤消问题),它每秒都会改变其值(CPU 使用率、时间等...).
使用 .NET Memory Profiler
(并通过简单地观察任务管理器)我注意到内存不断增长.更准确地说,我看到了越来越多的 UnmanagedMemoryStream
实时实例(我尝试了 GC.Collect()
,但显然什么也没做).
I'm using .NET 4.5 on Windows 7, and might find a memory leak.
I have a TextBlock
(not TextBox
- it's not the Undo problem), which changes its value every second (CPU usage, time, etc...).
Using .NET Memory Profiler
(and by simply watching task manager) I noticed the memory keeps on growing. To be more accurate, I see more and more live instances of UnmanagedMemoryStream
(I tried GC.Collect()
which obviously didn't do anything).
经过一些测试,我发现只有当我将TextBlock
字体设置为资源字体时才会出现此问题,如下所示:
After some tests, I've found out that this problem appears only when I'm setting the TextBlock
font to a resource font as follows:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Control.Foreground" Value="#CCCCCC"/>
<Setter Property="FontFamily" Value="pack://application:,,,/MyUIControls;component/./Fonts/#Noto Sans"/>
</Style>
我尝试直接从代码或通过绑定更新 Text
属性,两种方式的行为都相同.
I tried updating the Text
property directly from code or via Binding, it behaves the same for both ways.
底线:
设置 FontFamily
后,每次更新文本时 UnmanagedMemoryStream
的实例都会(永远)出现.当我不这样做时(设置 FontFamily
属性),内存是稳定的.
(顺便说一句,当我使用 Label
而不是 TextBlock
时也会发生这种情况)
Bottom line:
When the FontFamily
is set, instances of UnmanagedMemoryStream
keep on coming (forever) each time I'm updating the text. When I don't (set the FontFamily
property), memory is stable.
(BTW, it happens when I use Label
instead of TextBlock
as well)
看起来像是内存泄漏,但我找不到任何有关它的参考.
有关如何解决的任何建议?
It looks like a memory leak but I couldn't find any reference about it.
Any suggestions of how can it be solved?
推荐答案
FontFamily
在使用时泄漏 UnmanagedMemoryStreams
如果它来自嵌入式资源或相关资源小路.当 FontFamily
来自系统字体或绝对路径时,它不会泄漏.
A FontFamily
leaks UnmanagedMemoryStreams
when it is used if it was sourced from an embedded resource or a relative path. When the FontFamily
is sourced from a system font or absolute path, it does not leak.
您可以查看这里 并下载重现问题的项目.
You can look here and download the project that reproduces the problem.
解决方法:对于资源字体:将字体保存到临时文件夹并使用存储字体的绝对路径.对于相对路径字体:解析并使用绝对路径.
Workaround: For Resource fonts: save fonts into a temporary folder and use the absolute path to the stored font. For relative path fonts: resolve and use the absolute path instead.
这篇关于使用字体时 WPF TextBlock 内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!