这个定时器是否会从内存释放? [英] Will this Timer be released from memory?

查看:339
本文介绍了这个定时器是否会从内存释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中考虑这一对函数:

  void func1(){
DispatcherTimer tmr = new DispatcherTimer );
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick + = func2;
tmr.Start();

$ b $ func2(对象a,EventArgs b){
//每调用一次func1()就被调用
}

调用func1()一次后,func2()每5秒钟被调用一次,即使我失去了对我的引用因为它的范围限制在func1()中。这意味着计时器显然仍然在内存中,在调用func1()之后很长时间。我的问题是,如果我将它添加到func2():

pre $ void func2(object a,EventArgs b){
//每调用一次func1()就调用5次

((DispatcherTimer)a).Stop()
}

定时器会在垃圾收集后立即被拾取,还是会一直保留在内存中,直到程序退出?如果它留在内存中,我怎么能手动标记它(或做类似的事情)?



我有一个第二个问题(如果你想回答的话)是如果一个普通的Timer在这种情况下会有完全相同的行为,或者我应该知道这个差别很大。



谢谢!


Threading.Dispatcher类保存所有活动DispatcherTimers的列表。当您在Tick事件处理程序中调用Stop()时,计时器将从该列表中移除。现在不再有任何对计时器的引用。它最终会被垃圾收集。这是可以的,因为没有办法让定时器重新开始。毕竟,你无法获得任何参考,Tick事件处理程序是你最后一次拍摄的。


Consider this pair of functions in C#:

void func1() {
    DispatcherTimer tmr = new DispatcherTimer();
    tmr.Interval = TimeSpan.FromSeconds(5);
    tmr.Tick += func2;
    tmr.Start();
}

void func2(object a, EventArgs b) {
    // Called every 5 seconds once func1() is called
}

After calling func1() once, func2() is called every 5 seconds from then on, even though I lose the reference to my timer since its scope is restricted to func1(). That means that the timer is obviously still in memory, doing its thing, long after func1() was called. My question is, if I add this to func2():

void func2(object a, EventArgs b) {
    // Called every 5 seconds once func1() is called

    ((DispatcherTimer)a).Stop()
}

will the timer be picked up by garbage collection soon after, or will it continue to stay in memory until the program exits? If it stays in memory, how can I mark it for collection manually (or do something similar)?

A secondary question I have (if you feel inclined to answer) is if a regular Timer would have the exact same behavior in this situation or if there is a significant difference I should know about.

Thanks!

解决方案

The Threading.Dispatcher class keeps a list of all active DispatcherTimers. When you call Stop() in the Tick event handler then the timer will be removed from that list. There are now no longer any references to the timer. It will eventually be garbage collected. Which is okay because there is no way to get the timer started again. After all, you don't have any way to get the reference anymore, the Tick event handler was your last shot at it.

这篇关于这个定时器是否会从内存释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆