我有一个使用以下代码的Windows服务项目:
protected override void OnStart(string[] args)
{
InitializeScheduler();
var timer = new Timer {Interval = 10 * 60 * 1000};
timer.Elapsed += (ss, ee) => InitializeScheduler();
timer.Start();
}
private void InitializeScheduler()
{
_taskScheduler = new TaskScheduler() { Enabled = true };
// do something
}
在TaskScheduler类中:
private Timer _triggerTimer;
public TaskScheduler()
{
_triggerTimer = new Timer(1000);
_triggerTimer.Elapsed += (TriggerTimerTick);
}
当我在“ InitializeScheduler()”中创建“ TaskScheduler”实例时,_triggerTimer不会被释放,而是添加另一个计时器。我该如何处置它并重新启动InitializeScheduler()方法中的所有内容?
答案 0 :(得分:0)
在创建新计时器之前,请先处置计时器。
private void InitializeScheduler()
{
if( _taskScheduler != null)
_taskScheduler.Dispose();
_taskScheduler = new TaskScheduler() { Enabled = true };
// do something
}
TaskScheduler类:
private Timer _triggerTimer;
public TaskScheduler()
{
_triggerTimer = new Timer(1000);
_triggerTimer.Elapsed += (TriggerTimerTick);
}
public Dispose()
{
if(_triggerTimer != null){
_triggerTimer.Dispose()
_triggerTimer = null;
}