构造函数中声明的 C# 对象的垃圾收集
在以下代码中,我在类的构造函数中创建一个 DispatcherTimer。没有人对此进行参考。
根据我的理解,计时器应该在离开构造函数的作用域后一段时间由垃圾收集器回收。 但这并没有发生!即使在使用 GC.Collect() 强制进行垃圾回收之后,
幕后到底发生了什么?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100),
IsEnabled = true
}
.Tick += (s, e) =>
{
textBlock1.Text = DateTime.Now.ToString();
};
}
}
In the following code, I create a DispatcherTimer in the class's constructor. No one keeps reference on it.
In my understanding, the timer should be reclaimed by the garbage collector some time after leaving the constructor's scope.
But that doesn't happen! Even after forcing a garbage collection with GC.Collect()
What is going on under the hood?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100),
IsEnabled = true
}
.Tick += (s, e) =>
{
textBlock1.Text = DateTime.Now.ToString();
};
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
计时器相当特殊,因为它们通过调用
一些链接来获取自身
编辑:< br>
没有意识到它是一个
DispatcherTimer
- 它不是直接 root 而是间接(到Dispatcher
),这反过来又会导致相同的效果。 。Timers are rather special since they root themselves by calling
some links
EDIT:
Didn't realize that it was a
DispatcherTimer
- that doesn't root itself directly but indirectly (to theDispatcher
) which in turn leads to the same effect...当您只是构造一个
DispatcherTimer
时,没有什么可以阻止它被 GC 。但是,您设置了IsEnabled = true
,这将在计时器上调用Start()
。当这种情况发生时,这行代码将被执行:现在 Dispatcher 本身正在根计时器,这意味着它无法被 GC 处理。
When you just construct the a
DispatcherTimer
, nothing prevents it from be GCed. However, you setIsEnabled = true
, which will callStart()
on the timer. When that, happens, this line of code will be executed:And now the
Dispatcher
itself is rooting the timer, meaning it can't be GCed.它将被添加到将被扎根的
Dispatcher
队列中。It will be added to the
Dispatcher
queue which will be rooted.