相关疑难解决方法(0)

如何在处理已用事件时阻止计时器?

我有一个计时器,不需要同时处理其已用的事件处理程序.但处理一个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)

.net c# multithreading timer

14
推荐指数
2
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1

timer ×1