DynamicResourceを使用してアプリケーションレベルのリソースを参照すると、メモリリークが発生する可能性があります。DynamicResourceをアプリケーションレベルのリソースに使用すると、リークが発生する可能性があります。
詳細については、このWPFフォーラムpostを参照してください。それを再現する方法といくつかの回避策。
私の質問は次のとおりです。もしそうなら、どうやってそれを取り組んだのですか?
ちなみに、このリークが発生しない状況が多いようですが、おそらく最も良い質問は、このリークが発生し、発生しない状況はどういうものでしょうか?ここでは便宜上
はそれを再現するコードです:
Window1.xaml.csApp.xaml
<Application
x:Class="WeakReferences.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml"
>
<Application.Resources>
<SolidColorBrush x:Key="MyBrush" Color="SkyBlue"/>
</Application.Resources>
</Application>
Window1.xaml
<Window
x:Class="WeakReferences.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
>
<Grid>
<Button
Name="ReleaseButton"
Content="Release Reference"
Click="Button_Click"
/>
</Grid>
</Window>
public partial class Window1 : Window { object p; public Window1() { InitializeComponent(); p = new Page1(); } private void Button_Click(object sender, RoutedEventArgs e) { p = null; GC.Collect(); } }
Page1.xaml
<Page
x:Class="WeakReferences.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1"
Background="{DynamicResource MyBrush}"
>
<Grid>
</Grid>
</Page>
Page1.xaml.cs
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
~Page1()
{
Trace.TraceInformation("Page1 Finalized.");
}
}