gpt4 book ai didi

c# - 如何在处理经过的事件时阻止计时器?

转载 作者:可可西里 更新时间:2023-11-01 08:05:43 25 4
gpt4 key购买 nike

我有一个计时器,它不需要同时处理其经过的事件处理程序。但是处理一个 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();
}
}
}

最佳答案

您可以将 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();
}

关于c# - 如何在处理经过的事件时阻止计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/815104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com