Ofe*_*ear 1 c# garbage-collection timer
我有一个Timer函数,我从global.asax中的Application_Start调用它
这是班级:
public class AlertTimer
{
public AlertTimer()
{
//
// TODO: Add constructor logic here
//
}
static System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Start()
{
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 30000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
PresenceService ps = new PresenceService();
ps.GetAbsenceContacts(); //takes 10 seconds
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是PresenceService ps = new PresenceService();
,在计时器完成运行后,此类类型是否正在变清,或者GC将其保留在内存中并在每次OnTimedEvent运行时启动一个新类型.
谢谢!
结论:从代码中删除GC.TNX!
现在,我的问题是这个类是否类型PresenceService ps = new PresenceService(); 在计时器完成运行后,它会变得干净,或者GC将它保留在内存中并在每次OnTimedEvent运行时启动一个新的.
是.
PresenceService的实例将保留范围,因此需要进行垃圾回收.但是,由于GC大部分都是不确定的,所以它一直存在于内存中,直到它被回收为止.因此,对于那些做事物并且有生命周期的对象(比如定时器),最好调用某种类型的"关闭"方法.
但是,我遇到的更大的问题是为什么你在Web应用程序中运行计时器,以及为什么你觉得需要直接在垃圾收集器上调用任何方法.这通常表明您的应用程序存在问题.