我使用System.Timers.Timer启动计时器。有一个事件 偶尔会引发一次,每次此事件引发时我都会增加一个计数器。 如果计数器> 3,则我执行一种方法来执行操作,并且需要重复执行此操作。
我每N秒重置一次计数器,以从1开始再次对事件进行计数。 当计数器重置为0时,我需要停止由计时器触发的正在进行的操作,但是我无法停止它,即使计数器重置为0后,该方法仍继续执行。
我的程序具有以下结构:
class Program
{
static void Main(string[] args)
{
var counter = 0;
//Create timer
var delayTimer = new System.Timers.Timer
{
// Interval = 900000, // every 15 minutes
Interval = 45000, // debug
AutoReset = true,
};
// Start the timer
delayTimer.Start();
delayTimer.Elapsed += ((o, e) =>
{
// when timer elapses reset the counter
counter = 0;
// stop the timed action function which was executing every N seconds for counter > 3
TimedTask(1, false, "stop"); // stop the timer
});
// an event raises the counter
while (event)
{
counter++; // keeps track of events raised
if (counter > 3)
{
// take a specific action
TimedTask(30000, true); // start the timer to perform an action every 30 seconds
}
}
// to keep the application going
System.Windows.Forms.Application.Run();
}
}
// method to start a timer for repeating a task every N seconds, or stop the counter for this ongoing timed task
public static void TimedTask(int interval, bool autoreset, string stop = null)
{
//Create timer
var delayTimer = new System.Timers.Timer
{
Interval = interval, // every N seconds
AutoReset = autoreset, // true: repeat, false: don't repeat
};
if (stop != null)
{
delayTimer.Elapsed += ((o, e) =>
{
// if 'stop' passed as string, stop executing the task every N seconds
delayTimer.Stop();
});
}
else
{
// Start the timer
delayTimer.Start();
// Create the event handler
delayTimer.Elapsed += ((o, e) =>
{
// when timer elapses call the method below
RepeatedAction();
});
}
}
// repeated action method
public static void RepeatedAction()
{
// perform an action, repeat it every N seconds
}
}
我尝试发送一个额外的字符串参数“ stop”来取消注册计时器,但这不起作用。
我正在创建两个不同的计时器:一个用于重置计数器,另一个用于重复计时任务,是否可以通过创建计时器方法或其他方法将其最小化?预先感谢。