繁体   English   中英

将 DynamicResource 用于应用程序级资源可能会导致泄漏

[英]Usage of DynamicResource to an Application Level Resource Can Cause Leaks

似乎使用 DynamicResource 来引用应用程序级资源会导致发生 memory 泄漏。

请参阅此 WPF 论坛帖子以获取更多信息、如何重现它以及一些解决方法。

我的问题是:还有其他人遇到过吗? 如果是这样,你是如何解决它的?

顺便说一句,似乎有很多情况不会发生这种泄漏,也许最好的问题是:这种泄漏发生和不发生的情况到底是什么?

为方便起见,这里是重现它的代码:

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();
    }
}

第1页.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>

第1页.xaml.cs

public partial class Page1 : Page
{
    public Page1()
    {
        InitializeComponent();
    }

    ~Page1()
    {
        Trace.TraceInformation("Page1 Finalized.");
    }
}

Microsoft 已确认这是一个错误,并且已在 .NET 4.0 中修复。

据我所知,只有在使用 DynamicResource 来引用应用程序级资源的 object 从未成为可视化树的一部分时,才会重现此错误。 希望看到一些相反的证据……或者进一步澄清这种泄漏何时发生。

更新:此错误也已在 .NET 3.5 中修复。 有关详细信息,请参阅此修补程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM