我编写了一个测试程序,其中一个单一的按钮被定义为
运行此代码的期望是,尽管C#垃圾回收的时间不确定性,但两个
有人能告诉我为什么XAML
以下是上述程序的参考代码:
MainWindow.xaml:
Window
内容的XAML。在窗口加载时,该Button
被程序替换为窗口的内容,引用它的字段也被替换,都是由我通过编程创建的另一个Button
。之后使用弱引用跟踪这两个Button
对象,并以1/10秒的间隔轮询每个对象的IsAlive
属性。在第一次调用轮询方法之前,我会将对编程定义的Button
的根引用全部清除。运行此代码的期望是,尽管C#垃圾回收的时间不确定性,但两个
Button
对象最终都将被报告为垃圾收集。尽管编程定义的Button
表现出这种行为,通常在半分钟内,但XAML Button
从未被收集。我已经让程序运行了十多分钟,仍然看到这种行为。有人能告诉我为什么XAML
Button
对象没有被回收吗?特别是,我想知道垃圾回收阻塞引用在哪里,无论它是在我的代码还是在WPF实现中。也许它在XAML加载对象中。我是否正在查看某种内存泄漏?以下是上述程序的参考代码:
MainWindow.xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="150" Loaded="Window_Loaded">
<Button Name="btn" />
</Window>
MainWindow.xaml.cs :
namespace Test {
public partial class MainWindow : System.Windows.Window {
private System.WeakReference wr_xamlBtn, wr_programmaticBtn;
public MainWindow() {
InitializeComponent();
}
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e) {
// Immediately upon the window's loading, create a weak reference to the
// button %btn defined in XAML.
wr_xamlBtn = new System.WeakReference(btn);
// Replace references in %btn and this.Content to the XAML button with
// references to a programmatically-defined button. This would be
// expected to free the XAML button for garbage collection.
btn = new System.Windows.Controls.Button();
Content = btn;
// Create a weak reference to the programmatically-defined button, so that
// when (strong) references to it are removed, it will be eligible for
// garbage collection.
wr_programmaticBtn = new System.WeakReference(btn);
// Provides a polling mechanism to see whether either the XAML button or
// the programmatically-defined button has been collected.
var dt = new System.Windows.Threading.DispatcherTimer();
dt.Tick += Poll;
dt.Interval = System.TimeSpan.FromMilliseconds(100);
dt.Start();
}
void Poll(object sender, System.EventArgs e) {
// If the programmatically-defined button hasn't had its references
// removed yet, this does so. This makes it eligible for garbage
// collection.
if (btn != null)
Content = btn = null;
// Uses the console to show a timestamp and the state of collection of the
// XAML button and the programmatically-defined button.
System.Console.WriteLine(
string.Format(
"XAML button {0}, Programmatically-defined button {1} @ {2}",
wr_xamlBtn.IsAlive ? "Alive" : "Collected",
wr_programmaticBtn.IsAlive ? "Alive" : "Collected",
System.DateTimeOffset.Now));
}
}
}
App.xaml:
<Application x:Class="Test.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" />
Poll(.)
方法中调用System.GC.Collect();
只会导致编程定义的按钮立即被回收。我加入了这个方法调用并运行了五分钟,但对 XAML 按钮的期望效果没有产生。 - 80386 DX