Dường như việc sử dụng DynamicResource để tham chiếu đến tài nguyên cấp ứng dụng có thể gây ra rò rỉ bộ nhớ.Việc sử dụng DynamicResource cho một tài nguyên cấp ứng dụng có thể gây ra rò rỉ
Vui lòng xem diễn đàn WPF này post để biết thêm thông tin, cách tái tạo và một số cách giải quyết khác.
Câu hỏi của tôi là: có ai khác chạy vào nó không? Nếu vậy, làm thế nào bạn đã làm việc xung quanh nó?
Nhân tiện, dường như có nhiều tình huống mà sự rò rỉ này không xảy ra, và có thể câu hỏi hay nhất là: chính xác những tình huống mà sự rò rỉ này xảy ra và không xảy ra ở đâu?
Để thuận tiện ở đây là mã mà tái tạo nó:
App.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>
Window1.xaml.cs
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.");
}
}