如何阻止一个计时器在处理事件的经过?计时器、事件

2023-09-04 01:05:15 作者:安若少年初入梦

我有一个需要在同一时间不会处理其经过的事件处理程序的计时器。但是,处理一个已用事件的可以的干扰他人。我实现了以下解决方案,但什么感觉错了;好像是I应该使用计时器不同或使用穿线空间内的另一目的。计时器最后的效果最好,因为我确实需要定期检查状态,但有时检查将需要更长的时间比我的时间间隔。这是接近这一目标的最佳方式是什么?

  //成员变量
私人静态只读对象timerLock =新的对象();
私人布尔发现= FALSE;


// 别处
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.Start();


公共无效Timer_OnElapsed(对象发件人,ElapsedEventArgs E)
{
  锁定(timerLock)
  {
    如果(!找到)
    {
      发现= LookForItWhichMightTakeALongTime();
    }
  }
}
 

解决方案

您可以设置自动复位为false,然后显式复位定时器你完成处理后。当然,你如何真正处理这取决于你如何期望定时器操作。这样做,这样可以让你的定时器偏离实际指定的时间间隔(如将停止和重新启动)。您的机制将使每个间隔火和被处理,但它可能会导致未处理事件的积压,现在的处理,其中,导致要调用的处理程序中的定时器的期满邻近

  timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.AutoReset = FALSE;
timer.Start();


公共无效Timer_OnElapsed(对象发件人,ElapsedEventArgs E)
{
    如果(!找到)
    {
      发现= LookForItWhichMightTakeALongTime();
    }
    timer.Start();
}
 
事件倒数计时器的制作教程

I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event may interfere with others. I implemented the below solution, but something feels wrong; it seems like either I should be using the timer differently or using another object within the threading space. The timer seemed to fit best because I do need to periodically check for a status, but sometimes checking will take longer than my interval. Is this the best way to approach this?

// member variable
private static readonly object timerLock = new object();
private bool found = false;


// elsewhere
timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.Start();


public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
  lock(timerLock)
  {
    if (!found)
    {
      found = LookForItWhichMightTakeALongTime();
    }
  }
}

解决方案

You could set AutoReset to false, then explicitly reset the timer after you are done handling it. Of course, how you handle it really depends on how you expect the timer to operate. Doing it this way would allow your timer to drift away from the actual specified interval (as would stopping and restarting). Your mechanism would allow each interval to fire and be handled but it may result in a backlog of unhandled events that are handled now where near the expiration of the timer that cause the handler to be invoked.

timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
timer.Elapsed = Timer_OnElapsed;
timer.AutoReset = false;
timer.Start();


public void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
    if (!found)
    {
      found = LookForItWhichMightTakeALongTime();
    }
    timer.Start();
}