Mic*_*eth 14 .net c# multithreading timer
我有一个计时器,不需要同时处理其已用的事件处理程序.但处理一个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)
tva*_*son 15
您可以将AutoReset设置为false,然后在完成处理后显式重置计时器.当然,你如何处理它实际上取决于你期望计时器如何运作.这样做会使你的计时器偏离实际的指定间隔(如停止和重新启动).您的机制将允许触发和处理每个间隔,但是它可能导致积压未处理的事件,这些事件现在在接近计时器到期时处理,导致处理程序被调用.
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13139 次 |
| 最近记录: |