使用Timer(System.Timers.Timer)时遇到了一个特殊问题。我检查了我的代码,但我无法找到我的推理中的错误。我非常感谢对此的一些见解。
我想做什么 该程序有两个无限循环,一个在另一个内部(一个叫做keepRunning,另一个叫keepTrying)。没问题,如果按Ctrl-C,循环变得有限,程序优雅地结束。
在循环内部,我一直要求用户按回车键。 为什么呢?
好吧,我也有一个计时器。此计时器每3秒调用一次函数。如果调用此函数10次,则keepTrying循环应变为有限且主程序退出此循环。 (通过在控制台中打印清楚地表明这一点"没有尝试"以及"开始尝试"。
除非用户按回车键。如果他按下回车键,定时器将被重置,定时器被调用的次数也变为0.一切都重新开始。
嗯,它不起作用。不知何故,即使定时器过去事件被调用超过10次,它仍然被调用并且循环不会退出。
请查看我的代码。我将不胜感激任何使其成功的建议 感谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace TimerExample1
{
class Program
{
private static Timer aTimer;
private static bool keepRunning = true;
private static bool keepTrying = true;
private static int attempts = 0;
static void Main(string[] args)
{
//We manage to set the way to finish this program with CTRL+C
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true; //execution continues after the delegate
keepRunning = false;
keepTrying = false;
};
SetTimer();
while (keepRunning)
{
Console.WriteLine("Start trying");
keepTrying = true;
while (keepTrying)
{
if (attempts > 10) break;
Console.WriteLine("Press the Enter key to prevent the timer from firing off...");
Console.ReadLine();
//it was pressed so
aTimer.Stop();
aTimer.Start();
attempts = 0;
}//keep trying
Console.WriteLine("got out of trying");
}//keepRunning
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.WriteLine("\nPress the Enter key to exit the application...");
aTimer.Stop();
aTimer.Dispose();
Console.ReadLine();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(3000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
attempts++;
if (attempts > 10) keepTrying = false;
}
}
}
答案 0 :(得分:3)
代码中的问题是Console.ReadLine();
阻止了操作。它会在该位置停止,直到用户按下回车键。计时器增量尝试次数并设置keepTrying = false;
并不重要,因为您在ReadLine
上被阻止,因此未在循环中检查其值。您应该将其更改为使用未阻止的Console.KeyAvailable
。如果有一个密钥Console.ReadKey
,则与Enter进行比较。请注意,如果某个键可用,您应该阅读它,否则您将一直获得KeyAvailable,直到您清空输入缓冲区。