System.Timers.Timer 是可以重入的,就是说在一个timer正在执行的时候,如果下次定时器到期了,会有一个新的线程执行timer的动作,也就是发生了重入。
根据程序的逻辑,这种情况有可能是我们不希望发生的。可以通过加锁的方式解决此问题。见如下代码:
private readonly object objNotifyTimerLock = new object();
/// <summary>
/// 定时处理邮件发送任务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (Monitor.TryEnter(objNotifyTimerLock))
{
try
{
Application["Timer_Notify_LastActiveTime"] = DateTime.Now;
NotifyerMgr.Instance.Execute();
}
finally
{
Monitor.Exit(objNotifyTimerLock);
}
}
}
/// <summary>
/// 定时处理邮件发送任务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (Monitor.TryEnter(objNotifyTimerLock))
{
try
{
Application["Timer_Notify_LastActiveTime"] = DateTime.Now;
NotifyerMgr.Instance.Execute();
}
finally
{
Monitor.Exit(objNotifyTimerLock);
}
}
}