【发布时间】:2019-04-04 02:33:00
【问题描述】:
我有一个基于 .net 的 Windows 服务,其中包含以下伪代码。它只是进入循环并根据条件立即执行 DoTask() 或在 60 秒后执行。这样做是为了防止在 DoTask() 已经运行时重叠的计时器调用。
我的问题是 - 如果这样做,已经在 DoTask() 中运行的代码/对象将被垃圾收集吗?或者,由于定时器是从定时器调用的 DoTask() 中启动的,所以内存堆栈会不断增加?
//called once when the service starts
function_startup
{
mainTimer = new System.Timers.Timer();
mainTimer.Interval = 10;
mainTimer.Elapsed += OnTimedEvent;
mainTimer.AutoReset = false; // makes it fire only once
mainTimer.Start();
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
//some business logic goes here
DoTask();
}
private void DoTask()
{
//some business logic goes here
//will the code that is here be garbage collected eventually
//or will always stay in memory stack increasing the memory that the service takes while running?
//if condition a, run DoTask immediately again.
if (condition_a)
{
mainTimer.Interval = 10;
mainTimer.Start();
}
//else if condition b, sleep for a minute and then DoTask
else (condition_b)
{
mainTimer.Interval = 60000; //run after 60 seconds
mainTimer.Start();
}
}
【问题讨论】:
标签: c# timer windows-services