我有一个计时器,不需要同时处理其已用的事件处理程序.但处理一个Elapsed事件可能会干扰其他事件.我实施了以下解决方案,但感觉不对劲; 似乎要么我应该使用不同的计时器,要么在线程空间内使用另一个对象.计时器似乎最合适,因为我确实需要定期检查状态,但有时检查将花费比我的间隔更长的时间.这是解决这个问题的最佳方法吗?
// 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)